如何从<b>使用jQuery标记

How to extract bold text from a <b> tag using jQuery

本文关键字:使用 jQuery 标记 gt lt      更新时间:2023-09-26

我有一些(坏的)HTML正在尝试抓取,看起来像这个

<div class="MsoNormal" style="text-align: justify;">
 <span style="font-family: Georgia,&quot;Times New Roman&quot;,serif;">
 <span style="color: #c00000;">"<i style="mso-bidi-font-style: normal;">Book Name</i>" by 
 <b style="mso-bidi-font-weight: normal;">AUTHOR</b>. Release Date: 
 <b style="mso-bidi-font-weight: normal;">DATE</b>. Published by 
 <b style="mso-bidi-font-weight: normal;">PUBLISHER</b>
</div>

我需要用粗体提取三件事,即AUTHOR、DATE&出版商

我试过$('strong,b').each(...)之类的东西,但它给出了整个文本。

编辑:这是我正在使用的部分代码,基本上我想做的是从一组这样的div中获取所有细节。

$(".MsoNormal").each(function(index) {
   var book = {}
   var elem = $(this).text()
   elem = sanitizeString(elem) // Removes whitespaces and line breaks
   book["title"] = getTitle(elem) // Gets the book name, which is between double quotes
   //Get author,date & publisher here $('b') traverses everything again
 }
 })

使用map函数,如下例所示。get方法将返回一个数组,然后您可以自由地对该信息执行任何操作。

var text = $("b").map(function() {
  return $(this).text();
}).get();
alert(text);
alert("Bold text: " + text.join(" "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="MsoNormal" style="text-align: justify;">
  <span style="font-family: Georgia,&quot;Times New Roman&quot;,serif;">
 <span style="color: #c00000;">"<i style="mso-bidi-font-style: normal;">Book Name</i>" by 
 <b style="mso-bidi-font-weight: normal;">AUTHOR</b>. Release Date: 
 <b style="mso-bidi-font-weight: normal;">DATE</b>. Published by 
 <b style="mso-bidi-font-weight: normal;">PUBLISHER</b>
</div>

只需使用$('b')选择器:

$('b').each(function(index, element) {
    console.log(element.textContent);
});

或者,如果你想将它们存储在一个数组中,你可以使用.map方法:

var bold_words = $('b').map(function() { return this.textContent });
console.log(bold_words);
// ["AUTHOR", "DATE", "PUBLISHER"]