[英]jquery unbind event from multiple input fields in one go
I have requirement where I need to track changes to input fields in a particular div and trigger an event if something is changed. 我有必要在哪里跟踪特定div中输入字段的更改并在发生某些更改时触发事件。
I am using following code to accomplish that 我正在使用以下代码来实现这一目标
$('div.dc2-content:eq(1) input:not([aria-readonly])').each(function(){
var $elem = $(this);
$elem.data("oldval",$elem.val());
$elem.on("change",{ctx:this},setItemStatus);
});
This is working fine but the second part of the requirement is that the event should be triggered only once. 这工作正常,但要求的第二部分是该事件仅应触发一次。 Which means that
意思就是
For this part I wrote following function 对于这一部分,我编写了以下函数
function setItemStatus(event){
var $el = $(this);
if($el.val() != $el.data("oldval")){
console.log("Invoke Update Method");
//unbind the events so that it doesn't trigger the update twice.
$('div.dc2-content:eq(1) input:not([aria-readonly])').each(function(){
var $elm = $(this);
$elm.off("change");
});
}
}
But even after this change event is not unbinded it still triggers if I make a change in any other field of the form. 但是即使在未取消绑定此更改事件之后,如果我在表单的任何其他字段中进行更改,它仍然会触发。
I know I can put conditions to stop executing the code but I would like to unbind. 我知道我可以设置条件以停止执行代码,但是我想取消绑定。
You can use the Jquery's one method, instead of the on
. 您可以使用Jquery的one方法,而不要使用
on
。
$('div.dc2-content:eq(1) input:not([aria-readonly])').each(function(){
var $elem = $(this);
$elem.data("oldval",$elem.val());
$elem.one("change",{ctx:this},setItemStatus);
});
Then, you don't need to "off" the event anymore since that's what one
method do. 然后,您不再需要“关闭”事件,因为这是
one
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.