jQuery event delegation

后端 未结 4 2134
一向
一向 2020-11-27 08:40

I need some help with the callbacks. For some reason, they don\'t work really well.
I\'m making a game with jQuery. I have a

<
相关标签:
4条回答
  • 2020-11-27 08:44

    Don't use the click(), use on('click') and attach it to the document.

    Creating a handler this way, will ensure that any new elements will be able to trigger the event.

    0 讨论(0)
  • 2020-11-27 08:53

    $('fight') selects fight tag, not the tag with fight id. Try to use $('#fight') instead.

    0 讨论(0)
  • 2020-11-27 08:56

    Which version of jQuery are you using? You should probably use jQuery.on() in this situation since your click handler code probably gets executed before the button is actually available in the DOM.

    $("#button").on("click", "#yes", function (event) {
        // Your yes-button logic comes here.
    });
    

    For more details and possibilities, read about the .on(events [, selector ] [, data ], handler(eventObject)) method in the jQuery documentation:

    If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

    When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

    In this case, you want to delegate the event since your element is not yet available in the DOM when you're binding the event.

    0 讨论(0)
  • 2020-11-27 08:59

    You can't set a click handler on an element that doesn't exist. What you should do is use .on to bind a element further up the tree. Something like:

    $("#someparentelement").on("click", "#yes", function() {
        // your code
    });
    
    0 讨论(0)
提交回复
热议问题