javascript - DOM 树中所有子元素的一个监听器

标签 javascript dom input jquery

如何只有一个 keypress 事件,以便它可以被 DOM 树中的任何子元素触发。

例如我有这样的东西:

<table>
<tr>
  <td><input type="text" id="col_1" value="1"/></td>
</tr>
<tr>
  <td><input type="text" id="col_2" value="2"/></td>
</tr>
<tr>
  <td><input type="text" id="col_3" value="3"/></td>
</tr>
</table>

例如,当用户更改 id=col_3 上的值,然后更改 id=col_2 上的值时,我如何区分哪个输入触发了此事件?我需要能够将 input id 和它的 value 保存在 array 中,以便我可以阅读稍后再说。

最佳答案

您可以尝试使用 jQuery .on method ,

$("table").on("keypress", "input", function(event){
  alert($(this).attr("id"));// gets the input id
  alert($(this).val());// gets the input value
});

此代码将处理 <table> 中的所有输入标签。

如果你不想在每次击键时都执行这个监听器,给一些时间(3 秒)呼吸,试试这个代码 -

var timeoutReference;

$("table").on("keypress", "input", function(event){
    var el = this; // copy of this object for further usage

    if (timeoutReference) clearTimeout(timeoutReference);
    timeoutReference = setTimeout(function() {
        doneTyping.call(el);
    }, 3000);
});

$("table").on("blur", "input", function(event){
    doneTyping.call(this);
});

function doneTyping(){
    var el = this;
    // we only want to execute if a timer is pending
    if (!timeoutReference){
        return;
    }
    // reset the timeout then continue on with the code
    timeoutReference = null;

    //
    // Code to execute here
    //
    alert('This was executed when the user is done typing.');
    alert($(el).attr("id"));//id
    alert($(el).val());//value
}

关于javascript - DOM 树中所有子元素的一个监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18120070/

相关文章:

javascript - 如何使用顺序数组重新排序对象数组?

javascript - 如何通过javascript更好地将复杂样式写入元素?

javascript - 在 phantomjs 中访问 iframe 的 contentDocument

javascript - 帮助 if 语句 - 最少 3 个字符

ruby - 使用 "gets"从另一个奇怪的错误运行 ruby​​ 脚本

javascript - 专题图: mouseover

javascript - 通过修改 Ryan Fait 的代码来设置多个单选按钮的样式

javascript - 为什么我的 CoffeeScript/backbone.js 事件没有触发?

javascript - 无法在 'appendChild' : The new child element contains the parent dropdown issue 上执行 'Node'

c - 从csv文件读取并分成变量