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

时间:2009-06-25 11:03:16

标签: javascript jquery

我将文本存储在包含多个span标记的变量中 我想立刻获得每个范围内的所有内容。 我怎么能用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>

2 个答案:

答案 0 :(得分:4)

更新:此解决方案已根据评论中的其他问题进行了更新:

只需抓取父选择器的.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>

答案 1 :(得分:0)

如果我理解正确地形成对Jonathan的答案的评论,使用下面的HTML(存储在变量中):

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

你想得到:

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

您可以使用以下方式执行此操作:

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('');

然而,这有点难看,并且在DOM中执行此操作时无法正常工作,因为您将所有跨度包装在div中。 (要在DOM中完成这项工作,请获取div#bla的HTML,然后将其用作htmlStuff)