简体   繁体   中英

jQuery appending li to ul unclickable

i have the following code that adds data to unordered lists. The troublesome code is as follows:

$('li:not(:first-child)').click(function() {
    var clickedLi = this;
    $(this).parent().prepend(clickedLi);
    var selectedLi = $(this).text();
    alert(selectedLi);
 $(this).parent().parent().nextAll().children('ul').children().replaceWith('<li>Please select</li>');

    //ajax call
    var returnedData = "<li>Dataset1</li><li>Dataset2</li><li>Dataset3</li>";

    //populate next with returned data
    $(this).parent().parent().next().children('ul').append(returnedData);
});​

If you click on one of the options in the first ul, data gets added to the second ul. However, the list items under this ul are not clickable, and I need them to be so, so that 'chain' can be continued.

Where is the bug? Any help would be much appreciated. Thanks in advance.

Try with: (if you use jQuery greater than 1.6.8. )

$(document).on('click','li:not(:first-child)',function() {

http://api.jquery.com/on/

I can suppose, judging by your code, that you expect the freshly added li to inherit the behaviour you append to the existing ones. Unfortunately it cannot work with the code written that way.

You need to attach the click event in an "observable" way so newly added elements to the dom will get the event handler attached.

To do this, you must use the .on method. You can check its reference here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM