简体   繁体   English

如何在jQuery子选择器中使用event.target?

[英]How to use event.target inside jQuery child selector?

I want to check if a child-element of a clicked div has a certain class. 我想检查单击的div的子元素是否具有某个类。

So i do this: 所以我这样做:

$('.panel').on('click', function (event) { if($(".panel input").hasClass('h5_validator_error')) { event.stopPropagation(); } });

The problem: I have more then one .panel class. 问题:我只有一个.panel类。 Since my whole site gets generated by the user and json-files, i need a dynamic environment without ids . 由于我的整个网站都是由用户和json文件生成的,因此我需要一个没有id的动态环境。

So, actually my if-statement is preventing all .panel -clicks from doing their job. 因此,实际上我的if语句正在阻止所有.panel - .panel发挥作用。

I want to do something like this: 我想做这样的事情:

if($(event.target + ".panel input").hasClass('h5_validator_error')) { event.stopPropagation(); }

So i want to select all input - elements from the clicked div without having an array and loop through it. 所以我想从所有单击的div中选择所有输入-元素,而无需数组并遍历它。

Is this possible? 这可能吗? Or what is the most efficient way of selecting child-elements of the clicked one? 或者,选择被点击元素的最有效方法是什么?

You should rather use this to get the targeted element: 您应该使用this来获取目标元素:

$(this).find("input").hasClass('h5_validator_error');

or 要么

$('input',this).hasClass('h5_validator_error');

You shoud make the dom object $(event.target) and then apply the jquery method on it. 您应该创建dom对象$(event.target) ,然后在其上应用jquery方法。

Try this: 尝试这个:

$('.panel').on('click', function (event) {
    if($(event.target).find('input').hasClass('h5_validator_error')){
      alert('true');
    }
    else{
      alert('false');
    }
});

Working Example 工作实例

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

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