简体   繁体   English

如何使用jQuery在子元素中获取文本内部的文本

[英]How Can I get Text Inside an Element with Children using jQuery

I have text stored in a variable which contains several span tags. 我将文本存储在包含多个span标记的变量中。
I want to get all the contents inside every span at once. 我想立刻获得每个范围内的所有内容。 How can I do that with jQuery or javascript? 我怎么能用jQuery或javascript做到这一点?

<htmlText>
    Researchthe university has been given a 5 star rating in the current Research Assessment Exercise. It is one of the UK's leading technological universities, specialising in research to provide solutions critical to industry, commerce and the healthcare, voluntary and public sectors.
    <span class="NBResult"></span><span class="NBResult">Data transmission speed</span>
    <span>, green fuels,small business marketing needs, European bureaucracy and the treatment </span>
    <span class="NBSearchTerm">of</span>
    <span> </span><span class="NBSearchTerm">cancer</span>
    <span> are all under investigation at the university. </span>
</htmlText>

Update: This solution has been updated following additional questions in the comments: 更新:此解决方案已根据评论中的其他问题进行了更新:

Just grab the .text() property of the parent selector. 只需抓取父选择器的.text()属性即可。

var myWords = "<span>I</span><span> </span><span>like</span><span> </span><span>words.</span>";

/* "I like words" */
alert($(myWords).find("span").text());
alert($("p.words span").text());

<p class="words">
  <span>I</span><span> </span><span>like</span><span> </span><span>words.</span>
</p>

If I understand correctly form the comments to Jonathan's answer, with the follwoing HTML (stored in a variable): 如果我理解正确形成对Jonathan的答案的评论,使用下面的HTML(存储在变量中):

<div id='bla'>
    ASD
    <span>foo</span>
    sdf
    <span class='x'>bar</span>
</div>

You want to get: 你想得到:

<span>foo</span><span class='x'>bar</span>

You could do that using: 你可以这样做:

var htmlStuff = '<div id="bla">etc.</div>'; //the HTML
var ret = new Array();
$(htmlStuff).find('#bla').children('span').each(function(){
     var x = $(this).wrap('<div></div>').parent().html();
     ret.push(x);
});
var spanString = x.join('');

This is however kinda ugly, and wont work correctly when doing this in the DOM because you would wrap all your span's in divs. 然而,这有点难看,并且在DOM中执行此操作时无法正常工作,因为您将所有跨度包装在div中。 (To make this work in the DOM get the HTML of div#bla and then use that as htmlStuff) (要在DOM中完成这项工作,请获取div#bla的HTML,然后将其用作htmlStuff)

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

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