jQuery alert onclick on element's child?

前端 未结 7 1781
粉色の甜心
粉色の甜心 2020-12-29 09:10

I\'m using this code to display an alert on a certain element:

$(\"#resultsBox\").click(function (event) {
    console.log(\'a\');
    });

相关标签:
7条回答
  • 2020-12-29 10:03

    When you bind an event handler with .click() it applies to any elements that matched your selector at that moment, not to elements later added dynamically.

    Given your div is called "resultsBox", it seems reasonable to assume you are actually adding things to it dynamically to display the results of some other operation, in which case you need to use a delegated event handler:

    $("#resultsBox").on("click", "li", function (event) {
        console.log('a');
    });
    

    This syntax of the .on() method binds a handler to "#resultsBox", but then when the click occurs jQuery checks whether it was on a child element that matches the "li" selector in the second parameter - if so it calls your function, otherwise not.

    0 讨论(0)
提交回复
热议问题