2012-03-21 70 views
1

我有这段代码。JQuery获取文本以元素开始

<p>jQuery is free, open source software, dual-licensed under the <span>MIT License</span> or the GNU General Public License, Version 2.</p> 
<p><span id="elt">jQuery is a</span> cross-browser <span>JavaScript</span>library designed to simplify the client-side scripting of HTML. <span>It was released in January 2006</span> at BarCamp NYC by John Resig. Used by over 52% of the 10,000 most visited websites, jQuery is the most popular JavaScript library in use <span>today</span>.</p> 
<img src="character1.jpg" height="200"/> 
<p>jQuery is free, open source software, dual-licensed under the <span>MIT License</span> or the GNU General Public License, Version 2.</p> 
<p>... 

我想要得到的前500个字符与$(".elt")开始,像这样:

jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML.It was released in January 2006 at BarCamp NYC by John Resig. Used by over 52% of the 10,000 most visited websites, jQuery is the most popular JavaScript library in use today.jQuery is free, open source software, dual-licensed under the MIT License or the GNU General Public License, Version 2. 

只是文本,删除所有的HTML标记。

回答

4
$('#elt').parent().text().slice(0, 500); 

获取文本,需要500个字符以内

编辑:对不起,看问题不能代码示例。固定。

var node = $('#elt').parent(); 
var text = node.text(); 

while (text.length < 500) { 
    node = node.nextSibling; 
    if (node.nodeType === 1) { 
     text += node.text(); 
    } else if (node.nodeType === 3) { 
     text += node.nodeValue; 
    } 
} 

text = text.slice(0, 500); 
+0

对不起,我的英文太烂了,还有$('#elt')之前的文本,我只希望文本以$('#elt')开头。 – user615816 2012-03-21 12:13:28

+0

你能举几个比较小的例子,只有20个字符吗? – callumacrae 2012-03-21 12:14:23

+0

我的意思是,找到元素,并获得它的文本'text1'。 然后得到这个元素后面的所有文本,'text2',然后'(text1 + text2).slice(0,500);' – user615816 2012-03-21 12:40:09