javascript 检查元素是否包含特定的子元素

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

Check if an element contains a specific child element

javascriptjqueryhtmldomjquery-selectors

提问by lomse

I have many divs which sometimes contain links. I want check whether or not they have a link. This is my attempt:

我有很多divs 有时包含链接。我想检查他们是否有链接。这是我的尝试:

var container = $(this).closest('.content').find('.text');

    //Check if text contains a tags
    if(container+':has(a)'){
        alert('contain link'); 
    }
    else{
        alert('no link found');  //Alert "contain link" even if no link is found.
    }

By doing container.html()I can see the exact content of containerincluding anchor tags, but my code above will always say that it cannot find the anchor tag.

通过这样做,container.html()我可以看到container包含锚标记的确切内容,但是我上面的代码总是说它找不到锚标记。

Could someone tell me what I am doing wrong?

有人能告诉我我做错了什么吗?

采纳答案by Dallas

Change to this:

改成这样:

if(container.find("a").length){ ...

containeris a jquery object and .find()is a function of that object that finds elements within it. A length greater than 0 will mean it finds an anchor tag and it will evaluate to true.

container是一个 jquery 对象,并且.find()是该对象的一个​​函数,用于在其中查找元素。大于 0 的长度将意味着它找到了一个锚标签,并将评估为真。

Edit:

编辑:

Also, to explain why your example isn't working. When you do container+':has(a)', you are doing a string concatenation which runs toString()on your object (converting it to "[object Object]"). So you end up with the string "[object Object]:has(a)" which will always evaluate to true.

另外,解释为什么你的例子不起作用。当您这样做时container+':has(a)',您正在执行toString()在您的对象上运行的字符串连接(将其转换为“[object Object]”)。所以你最终得到字符串“[object Object]:has(a)”,它总是评估为真。

回答by Rory McCrossan

You can use the lengthproperty of a selector to determine if any elements were found. Try this:

您可以使用length选择器的属性来确定是否找到了任何元素。试试这个:

var $container = $(this).closest('.content').find('.text');

if ($('a', $container).length) {
    alert('Contains links'); 
}
else {
    alert('No links found');
}

回答by Vitaly Muminov

Change

改变

if(container+':has(a)'){  

To

if(container.has('a').size()){  

container is an jquery object, not a selector string

容器是一个 jquery 对象,而不是一个选择器字符串

回答by Suresh Atta

Yours will work if you change it to

如果您将其更改为

 if($(container+":has(a)").length > 0){

In docs

在文档中

The supplied selector is tested against the descendants of the matching elements

提供的选择器针对匹配元素的后代进行测试