Pergunta

I am dragging an li element, and dropping it to ul. I want to register click handler for this li element.

However, click event is not being fired.

            function initListClickEvent() {
                $("#list1 > li").click(function () {
                    $(this).css("background-color", "blue");
                    $(this).css("color", "white");
                });
            }

            $(document).ready(initListClickEvent);

            $(function () {
                $("#list1").droppable({
                    accept: 'li',
                    drop: function (e, ui) {
                        initListClickEvent();
                    }
                });
            })

What would be the solution to the problem? All the elements react on click (because their click event has been registered previously), except the one I have just dragged to the list.

Foi útil?

Solução

change it like

 function initListClickEvent() {
     $("#list1 > li").click(function () {
        $(this).css("background-color", "blue");
        $(this).css("color", "white");
    });
        $("#list1 > li").trigger("click");
    }

    $(document).ready(initListClickEvent);

    $(function () {
        $("#list1").droppable({
            accept: 'li',
            drop: function (e, ui) {
                initListClickEvent();
            }
        });
    });

Edit

If the elements are adding dynamically, you should use event delegation for that

$(document).on("click","#list1 > li",function(){
   $(this).css("background-color", "blue");
        $(this).css("color", "white");
});

It helps you to attach handlers for the future elements

Outras dicas

you should use delegate of jquery for dynamically added items

 $(function () {
            $("#list1").droppable({
                accept: 'li'
            });

$( "#list1" ).delegate( "li", "click", function() {
$(this).css("background-color", "blue");
$(this).css("color", "white");    });

});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top