VDS VDS - 4 months ago 7
HTML Question

Click event not working for dynamically added Li->span->id

Click event not working for dynamically added Li->span->id

case"101" : strLink = "<li style='cursor:pointer'><a data-scroll><span id=div101'>Form 101</span></a></li>"; $('.sidebar-nav').append(strLink); break;
---------------
$(".sidebar-nav").on("click", "#div101", function ()
{
console.log("Clicked on div101");
});


This is Not working. How can i make it work?

Answer

You have an extra quote in there, which is causing the browser to misinterpret the ID:

case"101" :   strLink = "<li style='cursor:pointer'><a data-scroll><span id='div101'>Form 101</span></a></li>"; $('.sidebar-nav').append(strLink); break;

You also have to make sure to add the handler after the element has been injected into the body. If the element isn't around, it will not register the click event.

Comments