【问题标题】:My jQuery plugin events not firing on multiple elements我的 jQuery 插件事件没有在多个元素上触发
【发布时间】:2011-05-28 20:52:08
【问题描述】:

我编写了一个 jQuery 插件来过滤选择列表选项。它适用于 一个 列表,但不适用于更多元素:http://jsfiddle.net/vgXPh/4/

$("select.filter").listFilter(); // doesn't work

$("select.filter:first").listFilter(); // works

我没有看到任何可能造成混乱的全局变量。我是否正确调用了我的绑定事件? JSLint 没有抱怨。我做错了什么?

【问题讨论】:

    标签: jquery-plugins jquery


    【解决方案1】:

    你应该用this.each()包围你的代码,像这样:

    $.fn.listFilter = function() {
        this.each(function() {
            (...)
        });
        return this;
    };
    

    【讨论】:

    • 嗯。我会试试的。这是我的第一个 jQuery 插件。
    • 有效!我会让 Jon Skeet 给你拿点咖啡来表示我的感激之情。
    • 在 .each(...) 内部,我不得不更改为 selectList = $(this);,因为循环中的 this 不会自动成为 jQuery 选择元素。
    • 你不是说在.each()之外吗?在循环中它可能与循环中的相同:)
    • this 已经是一个 jQuery 对象,它应该只是 this.each() :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    相关资源
    最近更新 更多