Reputation: 229
if($('#term').children().length == 0){
$("#term").append("<ul id='ulDynamic' class='ulDynamic'></ul>");
var i;
for(i=1;i<=3;i++){
var liDynamic = "Term "+i;
var liId = "Term"+i;
$("#ulDynamic").append("<li id="+liId+ " class='listDynamic'>"+ liDynamic +"</li>");
if(i==0){
$('#'+liId).click();
}
}
.click() is not working since liId is a dynamically created element. I want the first li element to be auto clicked when the page loads. Is there any other way to do it?
Upvotes: 10
Views: 32101
Reputation: 36551
use event delgation on
inside your ready function
try this
$(function(){
$('#term').on('click','li:first',function(){
//do your stuff
});
});
Upvotes: -4
Reputation: 100205
do something like:
$("#term").append("<ul id='ulDynamic' class='ulDynamic'></ul>");
var i;
for(i=1;i<=3;i++){
var liDynamic = "Term "+i;
var liId = "Term"+i;
var $li = $("<li />", {
"id" : liId,
"class" : 'listDynamic'
}).html(liDynamic).click(function() {
alert("clicked:" + this.id);
});
$("#ulDynamic").append($li);
}
$("#ulDynamic").find("li:first").trigger("click");
Demo :: jsFiddle
Upvotes: 13
Reputation: 27382
I have seen your ID is starting with Term
so you can use .on() to add click event on DOM that are added later.
Exapmple
$(document).on('click','[id^="Term"]',function(){
//code here
});
Upvotes: 8