簡體   English   中英

在文本區域顯示選定的文本

[英]Displaying the selected text in text area

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>

在這里,我試圖按用戶顯示選定的文本。 我需要顯示由用戶選擇的文本。但不幸的是事件沒有觸發.. 這段代碼有任何錯誤。 請給我解決方案..

您的相同代碼在小提琴中對我有用,而不是 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()函數上調用警報,該函數本身正在發出警報,而不是返回任何字符串值。

請檢查。

幾點建議:

在您的代碼中TextArea1是一個 ASP 控件,您不會像在給定代碼中那樣獲取或設置它的值。 要使其工作,您可以執行以下任何操作:

  1. 將 Asp textBox 更改為 HTML TextBot: 所以標簽將如下所示:

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

如果您想在后端訪問它,請包含runat="server"

  1. 更改腳本以正確獲取值,就像評論中建議的 Webruster 一樣。 或從此參考

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

    我還要說的一件事是,錨標簽。 由於兩個原因,無需顯示額外警報:

    • 該方法不返回任何內容
    • 內容已在被調用的方法中發出警報

所以<a>將如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM