简体   繁体   English

如何使用jquery检测点击元素动态添加?

[英]How to detect clicked element added dynamic using jquery?

How can I detect clicked element in code like this: 我如何在这样的代码中检测到单击的元素:

HTML: HTML:

<div class="foo">
  <a href=""><b>Foo</b></a>
</div>   
<div class="bar">
  <a href=""><b>Bar</b></a>
</div>

jQuery: jQuery的:

$('body').on('click', '.foo, .bar', function (e) {     
   if (detectElement == '.bar') {
     //
   }
}

I try $('this') but returned body not clicked element. 我尝试$('this')但返回的body未单击元素。 I try also e.target but I want get main element ( .foo or .bar ), not <a> / <b> 我也尝试e.target但我想获取主元素( .foo.bar ),而不是<a> / <b>

$('this') isn't right. $('this')不正确。 this is variable that contain clicked element. this是包含clicked元素的变量。 You can't use it as string. 您不能将其用作字符串。 Use .hasClass() to check element has specific class name. 使用.hasClass()检查元素是否具有特定的类名称。

$('body').on('click', '.foo, .bar', function (e) {
    if ($(this).hasClass('bar')) {
        // code
    }
});

 $('body').on('click', '.foo, .bar', function (e) { if ($(this).hasClass('bar')) console.log("is .bar"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="foo"> <a href="#"><b>Foo</b></a> </div> <div class="bar"> <a href="#"><b>Bar</b></a> </div> 

You could use .is() 您可以使用.is()

Check the current matched set of elements against a selector , element, or jQuery object and return true if at least one of these elements matches the given arguments. 针对selector ,元素或jQuery对象检查当前匹配的元素集,如果这些元素中的至少一个与给定参数匹配,则返回true

and The selector is not correct instead use event.currentTarget , , when you use $('this') is Element Selector (“element”) since you have no HTML element as this the condition does't works. 并且选择器不正确,而是使用event.currentTarget ,当您使用$('this')元素选择器(“ element”)时,因为您没有HTML元素, this该条件不起作用。

The current DOM element within the event bubbling phase. 事件冒泡阶段中的当前DOM元素。

$('body').on('click', '.foo, .bar', function (event) {
    if ($(event.currentTarget).is('.bar')) {
        //Your code
    }
});

Use the currentTarget attribute of the event callback. 使用event回调的currentTarget属性。

$('body').on('click', '.foo, .bar', function (e) {
  $(e.currentTarget).hasClass('foo') {
    alert('Foo has been clicked');
  }

  $(e.currentTarget).hasClass('bar') {
    alert('Bar has been clicked');
  }
});

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM