【问题标题】:jQuery plugin return this.eachjQuery 插件返回 this.each
【发布时间】:2016-08-25 22:44:41
【问题描述】:

我正在构建一个插件,我们称之为ptest,我希望能够使用以下方式调用它:

$(".myClassName").ptest();

由于我使用的是调用插件的元素中的属性,假设data-attribute 我现在知道返回this.each(...);必须
这是我的代码:

(function($){
    var op;
    $.fn.ptest = function(options) {
        op = $.extend({
            target: null,
            attribute: null
        }, options);

        return this.each(function(){
            op.target = $(this);
            op.attribute = op.target.attr("data-attribute");
            bind();
        });
    };
    function bind(){
        op.target.find('.clickable').bind('click',log);
    }
    function log(){
        console.log(op.attribute);
    }
}(jQuery));

我知道通过将op 作为全局变量,它将始终保留attributetarget 的最后一个值。如何使 op 变量为 .myClassName 的每个元素保留正确的值,同时能够从 logbind 函数访问每个 op

我觉得我需要以不同的方式声明函数和变量,但是如何?


我看过很多不同的问题和教程,这里有一些:

【问题讨论】:

  • 你用bindlog做什么?
  • @T.J.Crowder 在我的问题中我只留下了基本代码,在真正的代码中我使用op.attribute 来查询数据库,所以我需要每个属性都是正确的
  • 恕我直言,这并不能真正回答问题。
  • @T.J.Crowder 你能更好地描述你想知道的吗?
  • op.target.find('.clickable').bind('click',log); 绑定点击事件触发log

标签: javascript jquery plugins


【解决方案1】:

如果bindlog 确实需要访问循环中的特定元素,那么您需要在each 回调中定义它们,并将op 设为该回调的本地:

(function($){
    $.fn.ptest = function(options) {

        return this.each(function(){
            var op = $.extend({
                target: $(this)
            }, options);
            op.attribute = op.target.attr("data-attribute");
            bind();

            function bind(){
                op.target.find('.clickable').bind('click',log);
            }
            function log(){
                console.log(op.attribute);
            }
        });
    };
}(jQuery));

但根据您使用bindlog 的方式,可能还有其他可用选项。

【讨论】:

  • 做到了,出于某种原因,我以为我已经尝试过了!
猜你喜欢
  • 2015-01-13
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
  • 2014-04-23
相关资源
最近更新 更多