jQuery 用jQuery检查一个div是否有一个具有特定属性的孩子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5068117/
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-26 18:30:29  来源:igfitidea点击:

Check whether a div has a child with a certain attribute with jQuery

jqueryjquery-selectorsattributes

提问by vee

I'm trying to find the syntax to determine whether a div has a child div containing the data-roleattribute set to header. I've tried these things with no luck:

我试图找到语法来确定一个 div 是否有一个包含data-role设置为的属性的子 div header。我试过这些东西但没有运气:

$('div[data-role*="page"]').each(function(i) {
    if($(this).children('div').attr('data-role')=='header';) {
        alert("has header");
    }
});

$('div[data-role*="page"]').each(function(i) {
    if($(this).children('div[data-role*="header"]').length!=0;) {
        alert("has header");
    }
});

回答by Mark Coleman

In this example you have a trailing ;after !=0;

在这个例子中,你有一个尾随;!=0;

$('div[data-role*="page"]').each(function(i) {
    if ($(this).children('div[data-role="header"]').length != 0) {
        alert("has header");
    }
});

Example on jsfiddle.

jsfiddle上的示例

回答by Chris Laplante

Try:

尝试:

if ($('div[data-role*="page"]').has("div[data-role=header]").size() > 0)
    alert("Has header");

Reference:http://api.jquery.com/has/

参考:http : //api.jquery.com/has/

回答by David says reinstate Monica

If I'm reading this correctly then the following should work:

如果我正确阅读此内容,则以下内容应该有效:

$('div[data-role=page]:has(div[data-role])').css('border','1px solid #ccc');

to select any div that contains a child div with the attribute of 'data-role'.

选择包含具有“数据角色”属性的子 div 的任何 div。

JS Fiddle.

JS小提琴

While you seem to want to utilise an ifto trigger an alert(), this seemsunnecessary since the above will function as a selector. If no elements are matched by that selector then, in the use-case I demonstrate, no elements will be affected. On the other hand, if an element is, or multiple elements are, selected then those will be.

虽然您似乎想利用 anif来触发 an alert(),但这似乎没有必要,因为上面的内容将用作选择器。如果该选择器没有匹配任何元素,那么在我演示的用例中,不会影响任何元素。另一方面,如果一个元素或多个元素被选中,那么那些将被选中。

回答by Software.Developer

This will select those divs that are child elements (with data-role attributes set to header) that are children of a div.

这将选择作为 div 子元素的那些 div(将 data-role 属性设置为 header)。

$('div > div[data-role=header]')