how to implement a handler for a second click on a li of a different ul in jquery?

StackOverflow https://stackoverflow.com/questions/11101729

  •  15-06-2021
  •  | 
  •  

Вопрос

At the begging I have one ul:

<div id="ul1DivId">
    <ul id="ul1Id">
        <li>li1</li>
    </ul>
</div>

Than I have a javascript that will hide this div/ul and add another div with another ul:

$(document).ready(function () {
$("#ul1Id > li").click(function() {
                    //to prevent scroll firing this handler:
        event.preventDefault();

        $("#ul1DivId").hide();
        var someValue = "someValue";
        var outputUl2Html = "<div id=\"ul2DivId\">" +
        "<ul id=\"ul2Id\">" +
        "<li id=\"liXId\">> " + someValue + "</li>" +
        "<li id=\"clearLiId\">-clear-</li>" +
        "</ul>" +
        "</div>";
        //show ul 2
        $(outputUl2Html).insertAfter('#ul1DivId');

});
});

Than I get style="display: none; " in the div with id="ul1DivId". This is expected. And I get the new inserted div after the hidden div element. This is expected too.

I have another javascript that never gets fired when clicking clearLiId:

$(document).ready(function () {
    $("#clearLiId").click(function() {
        //I never reach here!!!!
    });
});

I tried also #ul2Id > li and #ul2Id > #clearLiId as selectors. Nothing gets the handler fired when I click on the #clearLiId li! Why? How do I get it to catch the click event? I want to show the first div (ul1DivId) again and remove the current div (ul2DivId).

Это было полезно?

Решение

You're missing event arguments and you need delegate event like following:

$(document).on('click', '#clearLiId', function() {
     //I never reach here!!!!
});


$("#ul1Id > li").click(function(event) {...
                                 ^ ----- missing event  

Note

I seems though $("#ul1Id > li"). is working for your first ul but it will not working for future coming uls. So it would be better if you assign class to each ul(already in DOM and will come in future) and change your selector. For example:

HTML

<div id="ul1DivId">
    <ul id="ul1Id" class="someClassToUl">
        <li>li1</li>
    </ul>
</div>

jQuery

$(".someClassToUl > li")...

Другие советы

You have to use live() function because the selector does not exist yet.

Attach an event handler for all elements which match the current selector, now and in the future.

$(document).ready(function () {
    $("#clearLiId").live(function() {
        //I never reach here!!!!
    });
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top