jQuery alert onclick on element's child?

前端 未结 7 1780
粉色の甜心
粉色の甜心 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:50

    Something like this should work

    $("#resultsBox").find("li").click(function(){
      alert("You clicked on li " + $(this).text());
    });
    

    This should work now: http://jsbin.com/ocejar/2/edit

    But anyway, also your example above using $("#resultsBox li") should work just fine. See here. However, using $("#resultsBox").find("li") should be a little faster in terms of performances.

    0 讨论(0)
  • 2020-12-29 09:54

    This should work.

    $("#resultsBox ul li").click(function (event) {
        console.log('a');
    });
    
    0 讨论(0)
  • 2020-12-29 09:54
    $("#resultsBox").find('li').click(function (event) {
        alert($(this).text());
        });
    
    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-12-29 09:59
    $("#resultsBox").click(function (event) {
        if(event.target.tagName.toLowerCase() == "li"){
             console.log('a');
        }
    });
    

    This will work for the dynamically added li elements.

    0 讨论(0)
  • 2020-12-29 09:59

    UPDATE after question edit:

    <div id="resultsBox">
      <ul id="myList">
        <li></li>
        <li></li>
      </ul>
    </div>
    
    
    $("#myList > li").click(function (event) {
    
            console.log('a');
    
            });
    

    Demo

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