Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.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插件创作:如何让我的插件在多组值上运行?_Javascript_Jquery_Jquery Plugins - Fatal编程技术网

Javascript jQuery插件创作:如何让我的插件在多组值上运行?

Javascript jQuery插件创作:如何让我的插件在多组值上运行?,javascript,jquery,jquery-plugins,Javascript,Jquery,Jquery Plugins,我有一个jQuery插件: (function( $ ){ $.fn.test = function(selector){ $this = this; $(selector).bind("click", function(){ methods.showvalue($this); }); }; var methods = { showv

我有一个jQuery插件:

(function( $ ){
    $.fn.test = function(selector){
        $this = this;

                $(selector).bind("click", function(){
                    methods.showvalue($this);
                });
    };
    var methods = { 
        showvalue   :   function($this){
            var output = "";
            $this.each(function(i,e){
                output += $(e).val();
            })
            alert(output);
        }
    }
})(jQuery);
使用此标记:

<form>
    <p>
        First section<br />
        <input type="text" class="test" name="firstValue" value="one" />
        <input type="text" class="test" name="secondValue" value="two" />
        <input type="text" class="test" name="thirdValue" value="three" />
        <button type="button" id="button1">push</button>
    </p>
    <p>
        Second section<br />
        <input type="text" class="test2" name="firstValue2" value="1" />
        <input type="text" class="test2" name="secondValue2" value="2" />
        <input type="text" class="test2" name="thirdValue2" value="3" />
        <button type="button" id="button2">push</button>
    </p>
</form>
不管我按哪个按钮,我总是得到一个带“123”的字符串。我的目标是在按下第二个按钮时得到“123”,而在按下第一个按钮时得到“onetwotree”


我错过了什么?为什么不这样做?

您必须在每个循环中引用对象:

return this.each(function() {  
   obj = $(this);  
});
或者在您的情况下:

return this.each(function() {  
  $this = $(this);
  $(selector).bind("click", function(){
    methods.showvalue($this);
  });
});
你需要申报

var $this = this;
否则,$将附加到窗口并变为全局

此外,您可能需要这样做,因此不需要附加多个回调:

$.fn.test = function(selector){
    var $this = this;
    $(selector).bind("click", function(){
       methods.showvalue($this);
    });
    return this;
};
编辑:演示

对不起,没有。这只是提醒“3”
$.fn.test = function(selector){
    var $this = this;
    $(selector).bind("click", function(){
       methods.showvalue($this);
    });
    return this;
};