我想突出显示html <body>
标记中的某些字词,但我想避免突出显示<a>
标记内的字词。如何才能做到这一点?通过突出显示我的意思是,强调并使单词变粗。
例如,我有这个HTML内容
<body>
<p>
This is sample text for the purpose of highlighting searched text. Please visit <a href="javascript:void(0)">www.sampleSite.com</a>
</p>
</body>
现在,当我搜索“sample”这个词时,我不想突出显示该锚标记中包含的 sample 这个词。
答案 0 :(得分:2)
/**
* jQuery plugin to replace text strings
*
* Taken from @link http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
*/
$.fn.replaceText = function( search, replace, text_only ) {
return this.each(function(){
var node = this.firstChild,
val, new_val, remove = [];
if ( node ) {
do {
if ( node.nodeType === 3 ) {
val = node.nodeValue;
new_val = val.replace( search, replace );
if ( new_val !== val ) {
if ( !text_only && /</.test( new_val ) ) {
$(node).before( new_val );
remove.push( node );
} else {
node.nodeValue = new_val;
}
}
}
} while ( node = node.nextSibling );
}
remove.length && $(remove).remove();
});
};
span
类highlight
元素的样式
span.highlight{
font-weight: bold;
text-decoration: underline;
}
// replace partial string occurrences with a span css styled element
// i.e. textsample => text<span class="highlight">sample</span>
$('p').replaceText(/(sample)/gi, '<span class="highlight">$1</span>');
或@Nick C.在评论
中的建议// replace full string occurrences with a span css styled element
// i.e. ONLY sample => <span class="highlight">sample</span>
$('p').replaceText(/\b(sample)\b/gi, '<span class="highlight">$1</span>');
该插件非常智能,不会替换元素的属性,也不会替换a
元素等元素内的文本...