2011-04-25 28 views
0

在下面的jQuery中,突出顯示跨度被插入到現有跨度中,創建一個嵌套跨度元素。是否可以修改腳本,以便它只在現有跨度中添加高亮類,而不是創建新跨度? (props and thanks to justkt的例子)jQuery在find()。each()遞歸期間在節點上插入一個類?

var content = jQuery('#content').html(); 

// append to a div to make sure there's a top-level tag. 
var html = jQuery("<div></div>").append(content).html(); 

// keywordList is a selector for a div containing spans of items representing the contents 
jQuery(".my_related_kw").find("span").filter(function() { 
    return html.indexOf(jQuery(this).html()) != -1; 
}).each(function() { 
    jQuery(this).html("<span class='highlight'>" + jQuery(this).html() + "</span>"); 
}); 

回答

2

使用addClassfilter後添加class='hightlight'現有<span>

jQuery(".my_related_kw").find("span").filter(function() { 
    return html.indexOf(jQuery(this).html()) != -1; 
}).addClass('highlight'); 
+0

+1甜。關於亞馬遜的jQuery書籍。我準備好潛入。有什麼建議嗎? – 2011-04-25 20:06:17

+0

無論有最新的版本和最好的評論。這就是我選擇的方式。我從Prototype轉換而來,所以我從來沒有一本書。 – 2011-04-25 20:13:22

0

使用addClass()函數。

}).each(function() { 
    jQuery(this).addClass('highlight'); 
}); 

按賈森的回答,你實際上並不需要的。每個()了,因爲addClass將在元素的集合工作。