检查元素是否包含特定的子元素
我有许多 div
s,有时包含链接。我想检查他们是否有链接。这是我的尝试:
I have many div
s which sometimes contain links. I want check whether or not they have a link. This is my attempt:
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.
}
通过执行 container.html()
我可以看到包含锚标签的容器
的确切内容,但我上面的代码总是会说它找不到锚标签。
By doing container.html()
I can see the exact content of container
including anchor tags, but my code above will always say that it cannot find the anchor tag.
有人可以告诉我我做错了什么?
Could someone tell me what I am doing wrong?
更改为: p>
Change to this:
if(container.find("a").length){ ...
容器
是一个jquery对象, .find()
是该对象的函数,可以在其中查找元素。长度大于0将意味着它会找到一个锚标签,并将它评估为true。
container
is 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 +':has(a)'
,你正在做一个字符串连接,它运行 toString()
您的对象(将其转换为[object Object])。所以你最终得到一个字符串[object Object]:has(a),它将始终评估为true。
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.