繁体   English   中英

如何使用jQuery获取元素的文本兄弟?

[英]How to get text sibling of element using jQuery?

我正在抓一个网站,我找到了这个

<table>
  <tr>
    <td>
      <b>Status:</b>ACTIVE;
      <b>Type:</b>CN - CONSTRUCTION
      <b>Added:</b>02/24/2012
    </td>
  </tr>
</table>

如何获取statustype和单独added

我知道我会得到投票,因为我没有发布任何经过审查的代码......但我似乎无法想到要尝试的东西!

这个网站有糟糕的HTML结构,我似乎找不到任何方式。

  • 使用jQueryElement.text()来获取所有文本。
  • 使用String#spplit分割字符串

 var text = $('#content').text(); var split = text.trim().split('\\n'); split.forEach(function(el) { var splitAgain = el.split(':'); console.log("Key: " + splitAgain[0].trim() + " Value: " + splitAgain[1].trim()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table> <tr> <td id="content"> <b>Status:</b>ACTIVE; <b>Type:</b>CN - CONSTRUCTION <b>Added:</b>02/24/2012 </td> </tr> </table> 

Javascript nextSibling属性获取元素的下一个文本兄弟。 您可以在td选择b元素并获取它的下一个文本。

 $("td > b").each(function(){ console.log(this.innerText +" = "+ this.nextSibling.nodeValue.trim()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <b>Status:</b>ACTIVE; <b>Type:</b>CN - CONSTRUCTION <b>Added:</b>02/24/2012 </td> </tr> </table> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM