这是我在网站上使用的插件的片段:
$.fn.extend({
limiter: function(limit, elem) {
$(this).on("keyup focus", function() {
setCount(this, elem);
});
function setCount(src, elem) {
...
}
}
});
仅当 elem
属性不是数组时,setCount()
函数才能正常工作 - 仅接受单个值。
我想更改它,以便可以将数组(在我的例子中为多项选择)传递给 setCount()
函数。
我认为解决方案是使用 jQuery.each()
迭代器,如下所示:
$.fn.extend({
limiter: function(limit, elem) {
$(this).on("keyup focus", function() {
$.each(elem, setCount)
});
function setCount(src, elem) {
...
}
}
});
问题是我还必须传递 this
对象,该对象指向接收 "keyup focus"
的对象,如第一个片段中的情况。
在给定场景中,如何将 this
对象传递给 $.each()
的回调属性?
最佳答案
尝试使用 bind
绑定(bind)上下文(警告不兼容 IE8):
$.each(elem, setCount.bind(this))
这使得每个 setCount 调用中的 this
上下文指向事件处理程序中的 this
。
关于javascript - jQuery.each() - 将额外的参数传递给回调参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29231974/