/**
* 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();
});
};
2.这是您可以用来实现替换的代码
// the array of affiliate links
var affiliates = [
['google', 'http://www.google.com/'],
['bing', 'http://www.bing.com/'],
['yahoo', 'http://www.yahoo.com/']
],
$p = $('p'), // the selector to search text within
i = 0, // index declared here to avoid overhead on the loop
size = affiliates.length, // size of the affiliates array
// again declared here to avoid overhead
reg; // the regex holder variable
// loop over all the affiliates array
for(i; i < size; i++){
// create a regex for each affiliate
reg = new RegExp('('+affiliates[i][0]+')','gi');
// finally replace the string with the link
// NOTE: do not forget to include the aforementioned plugin before this code,
// otherwise this won't work
$p.replaceText(reg, '<a href="'+affiliates[i][2]+'">$1</a>');
}
这是一个演示
3. 你需要做一些改变
您所要做的就是更改 jQuery 选择器和附属数组。其余的将由插件处理。该插件足够聪明,不会替换元素的属性。