【问题标题】:one listener for all child elements in the DOM treeDOM 树中所有子元素的一个侦听器
【发布时间】:2013-08-09 19:32:45
【问题描述】:

如何只有一个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 的值时,我如何区分哪个输入触发了此事件?我需要能够将 input idvalue 保存在 array 中,以便稍后阅读。

【问题讨论】:

  • 你如何使用 jQuery 或 dom 方法注册事件处理程序

标签: javascript dom input jquery


【解决方案1】:

你可以尝试使用jQuery .on method

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

此代码将处理 &lt;table&gt; 标记内的所有输入。

如果你不想在每次击键时都执行这个监听器,给一些时间(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
}

【讨论】:

  • 你会如何将它与这个答案结合起来:stackoverflow.com/questions/14042193/…
  • 我可以为它设置一个计时器,这取决于您要等待多长时间才能确定用户已停止输入,2 或 3 秒
  • 还有一个问题 :) 有没有办法将此 id 和值发送到 doneTyping() ?
猜你喜欢
  • 1970-01-01
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 2016-04-18
  • 2021-06-05
  • 2010-11-22
相关资源
最近更新 更多