Javascript each()-将额外参数传递给回调参数

Javascript each()-将额外参数传递给回调参数,javascript,jquery,Javascript,Jquery,这是我在我的网站上使用的插件的一个片段: $.fn.extend({ limiter: function(limit, elem) { $(this).on("keyup focus", function() { setCount(this, elem); }); function setCount(src, elem) { ... } } }); setCount(

这是我在我的网站上使用的插件的一个片段:

$.fn.extend({
    limiter: function(limit, elem) {
        $(this).on("keyup focus", function() {
            setCount(this, elem);
        });
        function setCount(src, elem) {
            ...
        }
    }
});
setCount()
函数只有在not数组中的
elem
属性-仅接受单个值时才能正常工作

我想对其进行更改,以便将数组(在我的示例中是多选)传递给
setCount()
函数

我认为解决方案是使用
jQuery.each()
迭代器,如下所示:

$.fn.extend({
    limiter: function(limit, elem) {
        $(this).on("keyup focus", function() {
            $.each(elem, setCount)
        });
        function setCount(src, elem) {
            ...
        }
    }
});
问题是,我还必须传递
this
对象,该对象指向接收到
的对象“keyup focus”
,就像第一个代码片段中的情况一样


在给定场景中,如何将
对象传递给
$的回调属性。each()

尝试使用
bind
绑定上下文(警告IE8不兼容):


这使得每个setCount调用中的
This
-上下文从事件处理程序指向
This

您可以保留对“第一个”
This
的引用,并在
setCount
中使用它:

$.fn.extend({
limiter: function(limit, elem) {
    var that = this;

    $(this).on("keyup focus", function() {
        $.each(elem, setCount)
    });
    function setCount(src, elem) {
        // use 'that' here
        ...
    }
}

}))

这项工作做得很好。非常感谢。
$.fn.extend({
limiter: function(limit, elem) {
    var that = this;

    $(this).on("keyup focus", function() {
        $.each(elem, setCount)
    });
    function setCount(src, elem) {
        // use 'that' here
        ...
    }
}