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

one listener for all child elements in the DOM tree

本文关键字:监听器 一个 元素 DOM      更新时间:2023-09-26

如何只有一个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_3id=col_2上的值时,我如何区分是哪个输入触发了此事件?我需要能够将inputid和它的value保存在array中,以便以后可以读取。

您可以尝试使用jQuery.on方法,

$("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
}