0

考虑以下 jQuery 插件代码:

(function($){
$.fn.MyPluginMethod= function() {
    $(this).after('<span>Hello</span>');
    };
})(jQuery);

如果我们这样调用这个函数: $('a').MyPluginMethod(); 对于每个 <a>存在的标签,它会在它之后添加一个<span>标签。

如果我们这样改变它:

(function($){
$.fn.MyPluginMethod= function() {
    title= $(this).attr('title');
    alert(title);
};
})(jQuery);

不会提醒每个 存在的标签的标题<a>,只会在第一次出现时提醒。

为什么会有这种行为?谢谢

4

2 回答 2

4

这是因为您正在创建插件的 1 个实例,因此alert()被调用一次。第一个示例span在 every 之后产生元素的原因a是因为after()jQuery 函数循环通过匹配的元素集。

要使后一个示例按您的意愿工作,您需要手动循环:

(function($){
    $.fn.MyPluginMethod= function() {
        this.each(function() {
            title = $(this).attr('title');
            alert(title);
        });
    };
})(jQuery);

您可以使用以下方法检查插件是否已在多个元素上实例化this.length

于 2013-08-12T12:33:47.107 回答
0

它会alert在您调用它时,也用于$.each为多个元素调用它,例如

HTML

<div title="test">test</div>
<div title="test123">test123</div>

脚本

(function($){
$.fn.MyPluginMethod= function() {
    return $(this).each(function(){
      title= $(this).attr('title');
      alert(title);
    });
};
})(jQuery);
$('div').MyPluginMethod();

更新小提琴

阅读http://learn.jquery.com/plugins/basic-plugin-creation/

于 2013-08-12T12:34:53.717 回答