Thursday 28 December 2017

javascript - How to bind function on different buttons?





I tried to bind alert on my
buttons:



for(var i=1; i<=3;
i++){

$('#' + i).live('click', function(){

alert(i);

});
};


It is
my html code:



            type="button" value="one">
value="two">

value="three">


But
I get 4 on all buttons. How to fix it to get correctly alert values? (1, 2, 3 and
etc..)



href="http://jsfiddle.net/sergey1986/UFjsM/">http://jsfiddle.net/sergey1986/UFjsM/



Answer




for (var i = 1; i <= 3; i++)
{
$('#' + i).live('click', function(i) {
return function()
{

alert(i);
};

}(i));
}


Note
that you are using .live wrong, the point is not to bind to
each element individually, but to figure out what each element have in common and use
that
selector:



$("input[type=button]").live(function()
{

alert(this.id);

});


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...