簡體   English   中英

你可以使用jquery來查看目標是否包含標簽?

[英]can you use jquery to see if a target contains a <b> tag?

所以,我有這樣的事情。

 var $list = $("div#item");

我在看:包含在選擇器中,但我不確定是否應用於標記或我是否應該執行以下操作:

 if($list.find("<b>"))return 1;
 else return 0;

推理:為使用內聯標記的程序添加功能,並希望維護結構。

目標:if(項目包含內聯b,u,i標簽)返回1; 否則返回0;

您可以將其簡化為單個選擇器.find("b,i,u")並返回布爾比較length > 0 如果在#item中找到任何標簽<b><i><u> ,則總長度將> 0

return $("#item").find("b,i,u").length > 0;

概念證明

編輯 :如果你真的想要一個number零或一個后面而不是boolean ,使用三元組:

return $("#item").find("b,i,u").length > 0 ? 1 : 0;
return document.querySelector("#item b, #item u, #item i") ? 1 : 0;

不需要jQuery。

如果您需要支持IE7及更早版本的瀏覽器,請嘗試以下方法:

var elem = document.getElementById('item');
return elem.getElementsByTagName('b').length
     + elem.getElementsByTagName('i').length
     + elem.getElementsByTagName('u').length == 0 ? 0 : 1;

也許使用.has()方法。

$('li').has('ul')

jquery有

你也可以用.has()函數做到這一點

我不確定它是最有效的,但我會使用.find

function hasInline(targetElement) { 
  return ($(targetElement).find('b,u,i').length > 0); 
}

我還建議擴展該功能,以便您可以指定要檢查的內聯標簽,如下所示:

// 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']);

如果你正在使用jQuery:

var styleElements = $('b,u,i', $list)

采用:

return (styleElements.length) ? 1 : 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM