2012-04-11 67 views
0
html_string "<span class=\"verse\"><strong>1<\/strong>\u00a0hello world how are you?,<span class=\"trans\" title=\"\u00a0Greek brothers.\">t<\/span> I am fine thank you.<\/span><span class=\"verse\"><strong>2<\/strong>\u00a0this world is very bad.<\/span><span class=\"verse\"><strong>3<\/strong>\u00aall me are good,<\/span>" 

我只是想提取其中具有類詩句跨度內的文本,它不應該包括與類反式從跨度文本。提取文本使用jQuery

結果必須是數組形式。

從上面的字符串我得導致這樣

["\u00a0hello world how are you? I am fine thank you","\u00a0this world is very bad.","\u00aall me are good,"] 

感謝

回答

1

如何:

var html_string = "<span class=\"verse\">" 
        + "<strong>1</strong>\u00a0hello world how are you?," 
        + "<span class=\"trans\" title=\"\u00a0Greek brothers.\">t<\/span> " 
        + "I am fine thank you." 
       + "</span>" 
       + "<span class=\"verse\">" 
        + "<strong>2</strong>\u00a0this world is very bad." 
       + "</span>" 
       + "<span class=\"verse\">" 
        + "<strong>3<\/strong>\u00aall me are good," 
       + "</span>"; 

// Build up the DOM in a hidden element we can parse through 
var $html = $('<div>',{html:html_string}).hide().appendTo('body'); 

// loop through each verse  
$html.find('.verse').each(function(i,e){ 
    // grab the verse, but first delete any span.trans 
    var verse = $(e).find('span.trans').remove().end().text(); 
    // console.log(verse); 
}); 
// remove the html from the DOM 
$html.remove(); 

你應該能夠循環播放,而不將其添加到DOM,但由於某種原因,我無法讓它工作。可能是因爲晚了,或者我的手指在晚上罷工。無論哪種方式,如果有人找到一種方法來做到這一點,但不附加它,請張貼,我會投票。

+0

和強制性演示:http://jsfiddle.net/rWYzb/ – 2012-04-11 02:24:30