Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/459.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery插件返回这个.each_Javascript_Jquery_Plugins - Fatal编程技术网

Javascript jQuery插件返回这个.each

Javascript jQuery插件返回这个.each,javascript,jquery,plugins,Javascript,Jquery,Plugins,我正在构建一个插件,我们称之为ptest,我希望能够通过以下方式调用它: $(".myClassName").ptest(); 由于我使用的是调用插件的元素的属性,比如说数据属性,我现在知道返回this.each(…)是必须的 这是我的密码: (function($){ var op; $.fn.ptest = function(options) { op = $.extend({ target: null, at

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

$(".myClassName").ptest();
由于我使用的是调用插件的元素的属性,比如说
数据属性
,我现在知道返回
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
作为全局变量,它将始终保留
属性
目标的最后一个值。如何使op变量为
.myClassName
的每个元素保留正确的值,同时能够从
log
bind
函数访问每个
op

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


我看了很多不同的问题和教程,以下是一些:

  • (当然)

如果
bind
log
确实需要访问循环中的特定元素,则需要在
每个
回调中定义它们,并使
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));

但是,根据您如何使用
bind
log
,可能还有其他可用的选项。

您使用
bind
log
做什么?@T.J.Crowder在我的问题中,我只留下了基本的代码,在真实的代码中,我使用
op.attribute
来查询数据库,因此,我需要在尊重的基础上对每个属性进行更正,但这并不能真正回答问题。@t.J.Crowder您能更好地描述您想知道的内容吗?
op.target.find('.clickable').bind('click',log)绑定了一个点击事件,该事件触发了执行该操作的
日志
,出于某种原因,我以为我已经尝试过了!