javascript - 在文本区域显示选定的文本

标签 javascript c# asp.net

function ShowSelection()
{
    var textComponent = document.getElementById('TextArea1');
    var selectedText;
    if (document.selection != undefined) {
        textComponent.focus();
        var sel = document.selection.createRange();
        selectedText = sel.text;
    }
    else if (textComponent.selectionStart != undefined) {
        var startPos = textComponent.selectionStart;
        var endPos = textComponent.selectionEnd;
        selectedText = textComponent.value.substring(startPos,endPos)
    }
    alert("You selected: " + selectedText)
}
</script>

<asp:TextBox id="TextArea1" TextMode="MultiLine" runat="server">/asp:TextBox>
<a href="#" onclick=alert(ShowSelection());>Click here to display the selected text</a>

这里我试图显示用户选择的文本。我需要显示用户选择的文本。但不幸的是事件没有触发。这段代码中有任何错误。请给我解决方案..

最佳答案

你的相同代码在 fiddle 中对我有用,但在asp.net中不起作用:

    <script>
  function ShowSelection() {
    var textComponent = document.getElementById('TextArea1');
    var selectedText;
    if (document.selection != undefined) {
      textComponent.focus();
      var sel = document.selection.createRange();
      selectedText = sel.text;
    } else if (textComponent.selectionStart != undefined) {
      var startPos = textComponent.selectionStart;
      var endPos = textComponent.selectionEnd;
      selectedText = textComponent.value.substring(startPos, endPos)
    }
    alert("You selected: " + selectedText)
  }

</script>

<input id="TextArea1" type="textarea" />
<a href="ShowSelection()" onclick="ShowSelection()">click me </a>

要点是为什么您再次对 ShowSelection() 函数调用警报,该函数本身正在发出警报,而不返回任何字符串值。

请检查。

关于javascript - 在文本区域显示选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36171376/

相关文章:

javascript - Buefy:锁定表头并仅使行可滚动

php - 如何在表单上制作文件或图像附件

javascript - 如何在谷歌地图中使用地址而不是经度和纬度?

c# - Visual Studio 2013 中的解决方案资源管理器未引用的图像

javascript - 如何从视频网址创建缩略图

javascript - 单击附加新容器

c# - 如何将文件路径从我的代码中取出并放入 mysql 的插入语句中?

c# - 如何连接 outlook 和 .net 框架

c# - RabbitMQ - QueueDeclare 永远挂起

asp.net - 检查 ViewState 中的值