2012-03-21 97 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