如何确定孩子是否在 Jquery 中被点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9504997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:54:26  来源:igfitidea点击:

How to determine if child was clicked in Jquery

jqueryonclick

提问by Du3

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

如果 onclick 事件绑定到父级,jQuery 中有没有办法判断哪个子级被点击?

For instance:

例如:

  $('#daddy').click(function () {
    // if($("#son").isClicked()){return true;}
    //return false;
  });

and the markup looks like:

和标记看起来像:

<div id="daddy">
  <span id="son"></span>
  <span id="daughter"></span>
</div>

回答by FishBasketGordo

The event handler you pass to clickwill receive an eventobject as its first argument. The targetof the event (i.e. the element that initiated the event) will be specified there.

您传递给的事件处理程序click将接收一个event对象作为其第一个参数。该target事件(即发起事件的元素)将被指定有。

Here's an example from the jQuery documentation:

这是jQuery 文档中的一个示例:

<!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>

回答by Pat

You can use the event.targetto determine what was clicked:

您可以使用event.target来确定点击了什么:

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

Here's a simple example.

这是一个简单的例子

回答by Eric Hodonsky

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);
        }
});

回答by frictionlesspulley

check this demoout

检查这个演示

$(function() {
    $('#parent').delegate('a', 'click', function(evt) {
        debugger;
        evt.stopPropagation();
        alert($(evt.currentTarget).attr('id'));
    });
});?

回答by blackpla9ue

Try this for an alternative

试试这个

$('#daddy span').click(function () {
    var clicked = $(this).attr('id');
    if(clicked == "son"){
        return true;
    }
    return false;
});

回答by Luca C.

use event.targetto get the really clicked node:

用于event.target获取真正点击的节点:

$('#daddy span').on('click',function(event){
    if(event.target.nodeName=='BUTTON'){//Was clicked a button
        ....
    }
    if(event.target.id=='id'){//Was clicked #id
        ....
    }
    ...
});