如何在表单中运行一些代码,只有当表单中的一些文本被用户选中时

jquery- how to run some code within a form only when some text within that form is selected by the user

本文关键字:表单 文本 用户 运行 代码      更新时间:2023-09-26

我想只在用户在表单中选择了一些文本时才运行一些代码-所选文本可能是表单中输入元素的标签,也可能是表单中直接给出的一些文本。

目前我正在使用下面的——

$('form').each(function(){
    // the 'this' below refers to a form- any element within the form is a child of the form...
    //hence the listener checks for focus being set to any element within any form of the web page...
    $(this).children().focus(function() {
  ......MY CODE HERE.............

是否有更好的方法来修改上面的代码,以便它只在用户选择了表单中的一些文本时才起作用?

试试这个;

$("form *").focus(function () { 
alert("focus"); 
});

有用于查看文本选择的javascript,但在某些方面它比DOM api更混乱。我没有一个完整的解决方案,但看看Rangy的一个相同的选择API和注册事件,如mouseup检查当前的选择