Reputation: 629
I have requirement like i will dynamically get a set of divs having random id's from my web service. And once it is added to my html i would like to bind some events to the id's. now my problem is if i am binding the event using for loop over the array of ID, when the scope of the loop finishes the events scope get destroyed.
ex:
var arrID={'1','2','3'};
for(var d in arr)
{
arrID.live("click",function() {});
}
//scope of for loop finishes here, hence the scope of click also.
How to overcome this problem? Thanks.
Upvotes: 2
Views: 148
Reputation: 319
var arrID=['1','2','3'];
for(var d in arrID)
{
$("#"+d).live("click",function() {});
}
Upvotes: 0
Reputation: 77996
You can't bind a click event to a JavaScript object. It has to be bound to a JQuery DOM object. Try this:
var arrID=['1','2','3'];
$.each(arrID, function(index, value) {
$('#' + value).live('click',function(){
// Do something
});
});
Here's a working demo. Notice only the first 3 created divs have the bound event: http://jsfiddle.net/FxwpC/
Upvotes: 3
Reputation: 4287
You probably want something like this:
$("#my-id-name-" +d).live("click", function() {
$(this).doSomeThing();
});
Upvotes: 1