[英]how to submit highlighted text from textarea into database
我必須在點擊事件中將突出顯示的文本從textarea保存到數據庫中,我該怎么做。 我從中找到了一些代碼,但對我不起作用。
$('#send').on("click", function(){ ShowSelection(); }); function ShowSelection() { var textComponent = $('#my-content span').val(); console.log(textComponent); var selectedText; if (textComponent.selectionStart !== undefined) {// Standards Compliant Version var startPos = textComponent.selectionStart; var endPos = textComponent.selectionEnd; selectedText = textComponent.value.substring(startPos, endPos); } else if (document.selection !== undefined) {// IE Version textComponent.focus(); var sel = document.selection.createRange(); selectedText = sel.text; } alert("You selected: " + selectedText); }
您的代碼有很多錯誤:
selectionStart
和selectionEnd
是表單元素(輸入,文本區域)的屬性,但是$('#my-content span')
顯然在查找<span>
元素。
$('#my-content span').val()
將返回一個字符串(在輸入的情況下,它是該輸入的值,但在您的情況下,它將為空,因為您將其應用於span元素。
textComponent.selectionStart
:由於textComponent
是字符串而不是HTML元素,因此textComponent
上沒有屬性selectionStart
。
-
<textarea>
元素的工作示例( 請參見此處 ):
var startPos = $('textarea')[0].selectionStart
// etc.
<span>
元素的工作示例( 請參見此處 ):
var selectedText = window.getSelection().toString()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.