[英]can you use jquery to see if a target contains a <b> tag?
so, i have something like this. 所以,我有这样的事情。
var $list = $("div#item");
I was looking at :contains in the selector, but i wasnt sure if that applied to markup or if i should do something like: 我在看:包含在选择器中,但我不确定是否应用于标记或我是否应该执行以下操作:
if($list.find("<b>"))return 1;
else return 0;
Reasoning: Adding functionality to a program which uses inline tags, and want to maintain structure. 推理:为使用内联标记的程序添加功能,并希望维护结构。
Goal: if(item contains an inline b, u, i tags) return 1; 目标:if(项目包含内联b,u,i标签)返回1; else return 0;
否则返回0;
You can simplify it down to a single selector .find("b,i,u")
and return the boolean comparison length > 0
. 您可以将其简化为单个选择器
.find("b,i,u")
并返回布尔比较length > 0
。 If any of the tags <b><i><u>
are found inside #item
, the overall length will be > 0
: 如果在
#item
中找到任何标签<b><i><u>
,则总长度将> 0
:
return $("#item").find("b,i,u").length > 0;
Edit : If you really want a number
zero or one back instead of the boolean
, use a ternary: 编辑 :如果你真的想要一个
number
零或一个后面而不是boolean
,使用三元组:
return $("#item").find("b,i,u").length > 0 ? 1 : 0;
return document.querySelector("#item b, #item u, #item i") ? 1 : 0;
No need for jQuery. 不需要jQuery。
If you need to support browsers IE7 and older, try this: 如果您需要支持IE7及更早版本的浏览器,请尝试以下方法:
var elem = document.getElementById('item');
return elem.getElementsByTagName('b').length
+ elem.getElementsByTagName('i').length
+ elem.getElementsByTagName('u').length == 0 ? 0 : 1;
你也可以用.has()函数做到这一点
I'm not sure it's the most efficient, but I would use .find
for this. 我不确定它是最有效的,但我会使用
.find
。
function hasInline(targetElement) {
return ($(targetElement).find('b,u,i').length > 0);
}
I'd also recommend expanding the function so you could specify whatever inline tags you wanted to check, like so: 我还建议扩展该功能,以便您可以指定要检查的内联标签,如下所示:
// NOTE: This will return true if the element has ANY of the tags provided.
function hasInlineTags(targetElement, listOfTags) {
return ($(targetElement).find(listOfTags.join(',')).length > 0);
}
// Call it with whatever tags you want.
hasInlineTags($("div#item"), ['b','u','i']);
if you're using jQuery: 如果你正在使用jQuery:
var styleElements = $('b,u,i', $list)
Use: 采用:
return (styleElements.length) ? 1 : 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.