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 关注
- 63 浏览
添加回答
举报