Javascript DOM树中所有子元素的一个侦听器
如何只有一个Javascript DOM树中所有子元素的一个侦听器,javascript,dom,input,jquery,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>
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
上的值时,我如何区分哪个输入触发了此事件?我需要能够在数组中保存和输入id
及其值
,以便以后可以阅读。您可以尝试使用jQuery
此代码将处理
标记内的所有输入
如果您不想在每次击键时都执行此侦听器,给它一些时间(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
}
您是如何使用jQuery或dom methodshow注册事件处理程序的?您会将其与以下答案结合起来吗:我可以为它设置计时器,这取决于,您希望等待多长时间才能确定用户已停止键入,2或3秒还有一个问题:)是否有任何方法将此id和值发送到doneTyping()?
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
}