2014-11-08 33 views
0

使用window.getSelection()工作正常的文本高亮顯示。但是,當我想突出顯示預選保存的文本不起作用。請幫我解決這個問題。向execcommand應用addclass方法

var highlight = 'Hello There'; 
document.execCommand('formatblock', false, 'p') 
var listId = highlight.focusNode.parentNode; // window.getSelection() not used 
$(listId).addClass("customClass"); 
+0

''highlight'是_string_的插件。 'getSelection'不返回一個字符串。它返回一個[Selection](https://developer.mozilla.org/en-US/docs/Web/API/Selection)對象。 – undefined 2014-11-08 13:20:42

回答

0

如果你想突出的DOM節點的內容包含搜索的文本,你應該使用jQuery的:contains選擇:

$('span:contains(Hello There)').addClass("customClass"); 

演示:http://jsbin.com/wifulereyi/2/

如果你想僅僅是爲了突出搜索到的文本,您需要先處理jQuery選擇結果,然後使用類似.wrapInner('<span class="highlight"></span>')的內容。在這種情況下,你最好不要使用像jQuery.highlight