Javascript 检查元素是否包含特定的子元素
我有许多Javascript 检查元素是否包含特定的子元素,javascript,jquery,html,dom,jquery-selectors,Javascript,Jquery,Html,Dom,Jquery Selectors,我有许多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'); //Aler
div
s,它们有时包含链接。我想检查他们是否有链接。这是我的尝试:
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()
我可以看到container
的确切内容,包括锚定标记,但上面的代码总是说它找不到锚定标记
有人能告诉我我做错了什么吗?改为:
if(container.find("a").length){ ...
container
是一个jquery对象,.find()
是该对象的一个函数,用于查找其中的元素。长度大于0意味着它将找到一个锚标记,并将计算为true
编辑:
此外,还要解释为什么您的示例不起作用。当您执行
container+':has(a)
时,您正在执行一个字符串连接,它在对象上运行toString()
(将其转换为“[object]”)。因此,您将得到字符串“[object]:has(a)”,该字符串将始终计算为true。您可以使用选择器的length
属性来确定是否找到任何元素。试试这个:
var $container = $(this).closest('.content').find('.text');
if ($('a', $container).length) {
alert('Contains links');
}
else {
alert('No links found');
}
改变
if(container+':has(a)'){
到
容器是jquery对象,而不是选择器字符串,如果将其更改为
if($(container+":has(a)").length > 0){
根据匹配元素的后代测试提供的选择器
container+”:has(a)
您认为对作为对象和字符串的操作数应用+
运算符的结果会是什么?这一点很好。不应将字符串与对象连接起来。它就是不起作用。谢天谢地,这也行不通,当您尝试用字符串连接容器时,它会将容器从jquery对象转换为字符串(“[object object]”),然后在尝试从该字符串创建jquery时会出现语法错误。这将起作用:container.has(“a”).length
,但没有理由检查>0
,因为0的计算结果将为false,而任何其他结果的计算结果将为true。这将不起作用-has()将实际返回容器的jquery对象子集,无论它是否包含元素,该子集都将计算为true—刚刚意识到“has”方法返回jquery对象,这是非常多的
if($(container+":has(a)").length > 0){