【问题标题】:Displaying the selected text in text area在文本区域显示选定的文本
【发布时间】:2016-03-23 15:40:22
【问题描述】:
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>

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

【问题讨论】:

  • 需要在Js中访问asp servercontrols 使用如下方式var textComponent = document.getElementById('&lt;%=TextArea1.ClientID %&gt;');
  • 上面的 javascript 代码似乎与基本 html 一起工作正常,您选择的文本方式错误,请看这里:stackoverflow.com/questions/1612413/…

标签: javascript c# asp.net


【解决方案1】:

你同样的代码在小提琴中对我有用,只是不是 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() 函数上调用警报,该函数本身正在发出警报,而不是返回任何字符串值。

请检查。

【讨论】:

    【解决方案2】:

    一些建议:

    在您的代码中TextArea1 是一个 ASP 控件,您不会像在给定代码中那样获取或设置它的值。要使其正常工作,您可以执行以下任何操作:

    1. 将 Asp 文本框更改为 HTML TextBot:因此标签将如下所示:

       <input type="text" id="TextArea1"/> 
      

    如果您想在后端访问它,请包含runat="server"

    1. 更改脚本以正确获取值,就像评论中建议的 Webruster 一样。或来自this reference

      var textComponent = document.getElementById('<%=TextArea1.ClientID %>');
      

      还有一点我要说的是,锚标签。由于两个原因,无需显示额外的警报:

      • 该方法没有返回任何内容
      • 内容已在被调用方法中发出警报

    所以&lt;a&gt; 将如下所示:

    <a href="#" onclick=ShowSelection();>Click here to display the selected text</a>
    

    【讨论】:

    • 嘿抱歉。以前没来。但现在它来得很好。但无法显示所选数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 2020-03-21
    • 2010-09-13
    相关资源
    最近更新 更多