Reputation: 793
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
for(var c=1; c<=5; c++){
var btn = $("<button>Button "+c+"</button>");
btn.click(new function(){
alert("You click button "+c);
});
$("body").append(btn);
}
</script>
</body>
</html>
Can someone explain to me why the click function get executed everytime the page is loaded? I am expecting the button to show an alertbox when it is clicked but unfortunately nothing happens! Any idea?
Upvotes: 0
Views: 77
Reputation: 87203
Remove new
from the button click handler.
Also, you need to update the code to get correct index of the button clicked as follow. Use wrap the code inside the for
in closure.
for (var c = 1; c <= 5; c++) {
var btn = $("<button>Button " + c + "</button>");
(function (c) {
btn.click(function () {
alert("You click button " + c);
});
}(c));
$("body").append(btn);
}
EDIT
A better way would be to use event delegation
with data-*
attributes to store information in HTML elements.
for (var c = 1; c <= 5; c++) {
var btn = $("<button class='myButton' data-title=" + c + ">Button " + c + "</button>");
$("body").append(btn);
}
$(document.body).on('click', '.myButton', function() {
document.write('You clicked ' + $(this).data('title') + ' button');
});
Upvotes: 2
Reputation: 4288
Just change your code to:
for(var c=1; c<=5; c++){
var btn = $("<button>Button "+c+"</button>");
btn.on('click', function(){
alert("You click button "+c);
});
$("body").append(btn);
}
You just have a mistake in your event assignment. Check jsFiddle
Upvotes: 0
Reputation: 3686
Remove the new
before the function. Creating a function in such a way invokes it as it takes it as a constructor.
for(var c=1; c<=5; c++){
var btn = $("<button>Button "+c+"</button>");
btn.click(function(){
alert("You click button "+c);
});
$("body").append(btn);
}
As you can see here:
var myFuncValue = new function() {};
Returns:
{}
While
var myFuncValue = function() {}
Returns
[Function]
Imagine that you are giving JQuery the myFuncValue
, it will try to invoke the first value which is an empty object in your case.
Upvotes: 1