How to determine if child was clicked in Jquery

后端 未结 6 826
广开言路
广开言路 2021-02-07 07:33

Is there a ways in jQuery to tell which child was clicked if the onclick event was binded to the parent?

For instance:

  $(\'#daddy\').click(function ()          


        
相关标签:
6条回答
  • 2021-02-07 07:39

    check this demo out

    $(function() {
        $('#parent').delegate('a', 'click', function(evt) {
            debugger;
            evt.stopPropagation();
            alert($(evt.currentTarget).attr('id'));
        });
    });​
    
    0 讨论(0)
  • 2021-02-07 07:41

    Try this for an alternative

    $('#daddy span').click(function () {
        var clicked = $(this).attr('id');
        if(clicked == "son"){
            return true;
        }
        return false;
    });
    
    0 讨论(0)
  • 2021-02-07 07:45

    This should be a different perspective at least:

    $('#parent').on("click", function(evt) {
            evt.stopPropagation();
            if($.inArray(evt.currentTarget, $(this).children())){
                console.log(evt.currentTarget);
            }
    });
    
    0 讨论(0)
  • 2021-02-07 07:47

    You can use the event.target to determine what was clicked:

      $('#daddy').click(function (e) {
          alert(e.target.id); // The id of the clicked element
      });
    

    Here's a simple example.

    0 讨论(0)
  • 2021-02-07 07:52

    The event handler you pass to click will receive an event object as its first argument. The target of the event (i.e. the element that initiated the event) will be specified there.

    Here's an example from the jQuery documentation:

    <!DOCTYPE html>
    <html>
    <head>
      <style>
    span, strong, p { 
      padding: 8px; display: block; border: 1px solid #999;  }
        </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
    
    <div id="log"></div>
    <div>
      <p>
        <strong><span>click</span></strong>
      </p>
    </div>
    <script>
    
    $("body").click(function(event) {
      $("#log").html("clicked: " + event.target.nodeName);
    });
    
    </script>  
    </body>
    </html>
    
    0 讨论(0)
  • 2021-02-07 08:00

    use event.target to get the really clicked node:

    $('#daddy span').on('click',function(event){
        if(event.target.nodeName=='BUTTON'){//Was clicked a button
            ....
        }
        if(event.target.id=='id'){//Was clicked #id
            ....
        }
        ...
    });
    
    0 讨论(0)
提交回复
热议问题