javascript - jQuery.each() - 将额外的参数传递给回调参数

标签 javascript jquery

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

$.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/

相关文章:

javascript - 使用 webpack-dev-server 时通过 HtmlWebpackPlugin 将模板写入磁盘

java - 如何从表中的 struts 标记发送带有操作 URL 的参数

javascript - 未捕获的类型错误 : Cannot read property 'name' of undefined - Reactjs

javascript - 无法在 jQuery 中使用 $this

javascript - jQuery - 当单击另一个链接时触发单击 div 内的另一个链接

javascript - Angular - 找不到名称 'Map'

javascript - React JS 在另一个组件内调用函数

javascript - 使用 jquery 更改 css 属性时防止触发窗口调整大小事件

jquery - 更新 $ ("body").css ("background") 导致 wpaudioplayer 刷新,适用于 Firefox 3.6 及以下版本

javascript - 如何转换数组中的一串数字