I created an ul dynamically, but when i used click function on the a tag inside the li tag, it only works after the second click. Here is my script
var uList;
$(document).ready(function () {
uList = $("#room");
$("#btn").click(function () {
appendLI();
});
});
function test() {
if ($("#room li").length > 0) {
$("li .roomName").on("click", function () {
alert($(this).text());
});
}
}
function appendLI() {
var li = $("<li/>").appendTo(uList);
var aaa = $("<a/>").prop("class", "roomName").prop("href", "javascript:test();").text("Google 1").appendTo(li);
}
Here is my HTML
<input type="text" autofocus/>
<ul id="room">
</ul>
<input type="button" id="btn" value="SET" />
var li = $("<li/>").appendTo(uList);You're trying to append to anundefinedvariable (uList) instead of an element. Second: using global variable is bad. Thirth: you shall defineappendLIfunction before using.