I have a jQuery plugin:
(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);
With this markup:
<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>
and this initializer:
$(document).ready(function(){
// first section
$(".test").test("#button1");
// second section
$(".test2").test("#button2");
});
Regardless of which button I push I always get a string with "123" in it. My goal is to get "123" when the second button gets pressed, and "onetwothree" one the first button is pressed.
What am I missing? Why isn't it behaving that way?
You need to declare
var $this = this;
Otherwise, $this gets attached to the window and becomes global.
Also, you might want this instead, so you don't attach several callbacks:
$.fn.test = function(selector){
var $this = this;
$(selector).bind("click", function(){
methods.showvalue($this);
});
return this;
};
EDIT: Demo http://jsfiddle.net/VSDLJ/
You have to refer the object in the each loop:
return this.each(function() {
obj = $(this);
});
Or in your case:
return this.each(function() {
$this = $(this);
$(selector).bind("click", function(){
methods.showvalue($this);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.