如何只有一个 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/