[英]Is it possible to detect which line, or function triggered a jquery change event on an element?
[英]jQuery change event triggered when element is built
我正在用jQuery构建一些动态选择列表。 更改它们后,我希望事件触发函数以刷新数据。
var selector = $('<select id="myid" />');
selector.append($('<option value>Option Placeholder</value>'));
// attach onChange event to select list
selector.bind('change', doUpdate(this));
我的问题是每次构建选择列表时都会触发change
事件。 我不确定触发如何发生-我希望它仅在change
发生时才触发change
事件!
执行此操作时:
selector.bind('change', doUpdate(this));
您期望发生的事情是绑定事件处理程序以执行doUpdate
函数,并将this
作为参数传递。
那不是正在发生的事情。 相反,它的作用是立即调用doUpdate(this)
,然后尝试将该函数调用返回的值设置为change
事件的事件处理程序。
您可以简单地执行以下操作:
selector.bind('change', doUpdate);
jQuery将处理的值, this
对你(这将是触发事件的元素),所以你不需要将它传递给函数作为参数。
您必须了解函数调用和函数引用之间的区别。 每个回调都应作为函数引用(或匿名函数)提供,而不应作为函数调用提供。
区别在于函数名称后的括号()
。
selector.bind('change', doUpdate);
编辑:请确保更新doUpdate
函数。 它会使用this
关键字自动访问触发更改的元素,因此您无需将其作为参数传递。
您的事件收集方法错误。 对于事件附件,您应该传递函数。 在这里,您正在执行函数并传递返回值。
var selector = $('<select id="myid" />');
selector.append($('<option value>Option Placeholder</value>'));
// attach onChange event to select list
selector.bind('change', function(){ doUpdate(this) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.