2014-05-01 100 views
0

所以我试图选择2个html标签之间的一些文本。它应该是非常简单的,但我似乎无法弄清楚。在标签之间选择纯文本

HTML:

<article> 
    width 
    <span class="Punctuation">:</span> 
    80% 
    <span class="Punctuation">;</span> 
</article> 

所以我想选择的单词Width和价值,80%每个存储在不同的元素。 最终的结果会是这样的:

<article> 
    <span class="Property">width</span> 
    <span class="Punctuation">:</span> 
    <span class="Value"> 80%</span> 
    <span class="Punctuation">;</span> 
</article> 

有没有人对如何做到这一点的想法?


---编辑---

我已经打上批复正确的答案,但有什么办法,使之清洁?

+0

这是否帮助?:http://stackoverflow.com/questions/822452/strip-html-from-text-javascript – MarkP

+0

将单词包装在div元素中,并在jquery中使用text()方法 –

+0

我试图从元素中的文章中包装纯文本。 .text()不起作用,因为它选择了“宽度”和“80%”两者。我需要单独选择它们。 看看我期望的结果。 “width”和“80%”都是 Brannie19

回答

4

您可以使用:

$('article').contents().filter(function() { 
    return this.nodeType === 3 && $.trim(this.nodeValue).length; 
}).first().wrap('<span class="Property" />'); 

$('article').contents().filter(function() { 
    return this.nodeType === 3 && $.trim(this.nodeValue).length; 
}).last().wrap('<span class="value" />'); 

Fiddle Demo

+0

非常感谢您的答案:)它的作品非常漂亮! – Brannie19

+0

好的答案+1我正在研究一个更长的例子。 (http://jsfiddle.net/6her5/1/),但不会接近您的解决方案。 – jvv

1

使用jQuery的.text() - http://api.jquery.com/text/

$('.Punctuation').text(); 
$('.Value').text(); 
+0

这将选择标点符号范围内的所有文本。我尝试选择的文本不是在跨度中,而是在父元素中。 – Brannie19