2013-03-14 113 views
2

我正在開發一個函數來突出html內部的div,我已經檢查過一些答案,但我沒有找到任何解決方案,我的情況。事情是,我居然有功能不會在同一時間,例如與2雙HTML標籤的工作:使用JavaScript突出顯示html文本

有了這個HTML代碼:

<span>Les malalties vasculars cerebrals (MVC) 
     conegudes també com a <i>feridures o ictus</i> representen la tercera causa de 

而這個功能的使用jQuery

jQuery.fn.highlight = function(pat) { 
function innerHighlight(node, pat) { 
    var skip = 0; 
    if (node.nodeType == 3) { 
    var pos = node.data.toUpperCase().indexOf(pat); 
    if (pos >= 0) { 
    var spannode = document.createElement('span'); 
    spannode.className = 'highlight'; 
    var middlebit = node.splitText(pos); 
    var endbit = middlebit.splitText(pat.length); 
    var middleclone = middlebit.cloneNode(true); 
    spannode.appendChild(middleclone); 
    middlebit.parentNode.replaceChild(spannode, middlebit); 
    skip = 1; 
    } 
    } 
    else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { 
    for (var i = 0; i < node.childNodes.length; ++i) { 
    i += innerHighlight(node.childNodes[i], pat); 
    } 
    } 
    return skip; 
} 
return this.length && pat && pat.length ? this.each(function() { 
    innerHighlight(this, pat.toUpperCase()); 
}) : this; 
}; 

jQuery.fn.removeHighlight = function() { 
return this.find("span.highlight").each(function() { 
    this.parentNode.firstChild.nodeName; 
    with (this.parentNode) { 
    replaceChild(this.firstChild, this); 
    normalize(); 
    } 
}).end(); 
}; 
  1. 列表項

如果我搜索: 「萊斯」 的作品

如果我搜索:「feridures」作品罰款也。

但如果我搜索「com feridures」功能不higlight我的文本。

這是我需要完成我的應用程序的唯一事情。

+7

「這是我需要完成我的aplication的唯一的事情。」著名遺言 – 2013-03-14 18:49:23

回答

1

問題不在於HTML標籤,它的確如此,但它與兩個標籤無關。事實是,你的應用程序正在搜索文字文本,這意味着它發現「com feridures」而不是「feridures」,所以沒有匹配。

您可以使用jQuery先將該跨度的HTML去除,然後它將起作用。

$(".highlight").html($(".highlight").text()); 

例子:http://jsfiddle.net/calder12/nJ5mQ/