Sha*_*laG 7 jquery replace contains nodevalue
我需要使用jQuery搜索文档来查找特定单词.它实际上是一个品牌名称,无论在何处使用,都必须是粗体和斜体.
我可以使用:contain
但仅基于单个元素.我需要能够通过锚点,列出div等.
$( "a:contains('brand name')" ).html().replace('brand name'....
Run Code Online (Sandbox Code Playgroud)
任何想法,将不胜感激.
更新:我已经实现了这个目的,并取代了页面上的所有内容,但我现在需要用类包装.如此接近但却难以接受这一点.我们将再次感谢您的想法.
$("body *").contents().each(function() {
if(this.nodeType==3){
this.nodeValue = this.nodeValue.replace(/brandname/g, 'colour');
}
});
Run Code Online (Sandbox Code Playgroud)
$.fn.ignore = function(sel){
return this.clone().find(sel||">*").remove().end();
};
function rebrand(el, word){
if (!word.length && !el) return;
var $el = $(el), html = $el.ignore("script").html(),
rgx = new RegExp("(?![^<]+>)("+ word +")", "g");
$el.html( html.replace(rgx, "<span class='brand'>$1</span>") );
}
$(function() { // DOM ready
// !!! IMPORTANT: REBRAND FIRST !!!
rebrand("body", "Brand Name");
// so the following code will not break on lost events, data bindings etc...
// Other DOM ready code here like:
$("button").click(function(){ $(this).css({color:"red"}); });
});
// Other JS, jQ code here...
Run Code Online (Sandbox Code Playgroud)
.brand{
color: rgba(255,0, 100,0.4);
font: italic normal bold 1em/1 sans-serif;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>Title with Brand Name!</h1>
<p>
Change styles only to Brand Name!<br>
but don't mess with <a href="#">links to Brand Name are cool</a><br>
<button>Button with Brand Name works!</button>
</p>
<ul>
<li>Other Brand</li><li>Brand Name</li><li>Brandy</li>
</ul>
</div>
<div>
<h2>Subtitle <i>and italic Brand Name</i></h2>
<p>The HTML will not get messed cause of Brand Nameing<br>
Paragraph with a <b> tag <b>bold Brand Name actually</b></p>
<code>This is a code tag with a Brand Name :)</code>
</div>
Run Code Online (Sandbox Code Playgroud)
感谢这两个答案:
jQuery.ignore插件
突出显示单词(忽略HTML标签的名称)
归档时间: |
|
查看次数: |
295 次 |
最近记录: |