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/

相关文章:

c# - 加密包含 key 的查询字符串

c# - 更新对象的通用方法错误( Entity Framework 4)

javascript - ValidatorEnable 不禁用 requiredfieldvalidator

javascript - 捕获无序列表中 anchor 元素的点击

c# - 字典包含它时不会从不同的类返回值

asp.net - 如何跟踪对 Linq-to-sql DataContext 的查询

c# - 如何快速删除然后将多个记录插入数据库

asp.net - 什么是 SQL Server 报告服务?

Innerhtml 的 Javascript 帮助

javascript - JavaScript 中 0.3 的字面表示