jQuery alert onclick on element's child?

前端 未结 7 1907
粉色の甜心
粉色の甜心 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 09:57

    Your code as you have it should be working: http://jsfiddle.net/GxCCb/

    Its important to note that the elements you're trying to attach the event handler to must exist when the code is evaluated. If it is added at a later time, then you must use on() (v1.7+) or delegate() (< 1.7), which is used for event delegation and allows the elements to be referenced if they are added later..

    Using on():

    $("#resultsBox").on('click', 'li', function (event) {
        alert(this.innerHTML);
        });
    

    Demo: http://jsfiddle.net/7Lz2Y/

    Using delegate():

    $("#resultsBox").delegate('li', 'click', function (event) {
        alert(this.innerHTML);
        });
    

    Demo: http://jsfiddle.net/XwYs5/

    However, there are plenty of other methods for attaching the event handler for elements that exist prior:

    $("#resultsBox").find('li').click(function (event) {
        alert(this.innerHTML);
        });
    

    Demo: http://jsfiddle.net/74Q7p/

    $("#resultsBox ul > li").click(function (event) {
        alert(this.innerHTML);
        });
    

    Demo: http://jsfiddle.net/a28U5/

提交回复
热议问题