1 回答

TA貢獻1765條經驗 獲得超5個贊
首先,函數實際上應該返回選定的文本getSelectedText
function getSelectedText(){
var selectedText = '';
if (window.getSelection) selectedText = window.getSelection().toString();
return selectedText;
// Or even better using ternary operator: return window.getSelection ? window.getSelection().toString() : '';
}
然后,正如不可思議的帽子所說,你應該糾正你處理事件的方式,可能如下,因為我通常使用獲取API來實現這種目的:-
// Only fire the ajax when user double click any text/selectables
$('#selectable').on("dblclick", function () {
// Marked contants since it won't change
const selected_text = getSelectedText();
// Make sure you check if the string is not empty before you do the request too
if(selected_text.trim().length > 0)
// Then do the request and process the output
$.ajax({
url: "dictionary.php", // php file path
method: "POST", // send data method
data: {"selected_text": selected_text}, // data to send {name: value}
success: function(data){
alert(data);
}
});
});
- 1 回答
- 0 關注
- 77 瀏覽
添加回答
舉報