jQuery使用replaceText和variable替换文本

时间:2011-01-01 19:42:19

标签: javascript jquery replace

我试图从http://benalman.com/projects/jquery-replacetext-plugin/

实现replaceText jQuery插件

但代码执行时没有任何反应。

感谢任何线索。 诚挚 马雷克

/**
 * jQuery Plugin replaceText
 **/

(function($){  
$.fn.replaceText=function(b,a,c){  
    return this.each(function(){  
        var f=this.firstChild,g,e,d=[];  
        if(f){  
            do{  
                if(f.nodeType===3){  
                    g=f.nodeValue;  
                    e=g.replace(b,a);  
                    if(e!==g){  
                        if(!c&&/</.test(e)){  
                            $(f).before(e);  
                            d.push(f)  
                        }else{  
                            f.nodeValue=e  
                        }  
                    }  
                }  
            }while(f=f.nextSibling)  
        }  
        d.length&&$(d).remove()  
    })  
}  
})(jQuery);  

/**
 * variable containing content of q variable from google referer
 **/

var querywords = "Some+text+from+google%20referer";

/**
 * function for replace each word from body with its "marked" version
 * that is after handled by css propetry for "mark" element
 **/

$(document).ready(function ( ) {
if(window.querywords !== undefined){
    var qw = window.querywords.replace('%20','+');
    qw = qw.replace(' ','+');
    var splited = qw.split("+");
    for(var q in splited){
        $('body :not(textarea)').replaceText( /\bsplited[q]\b/gi, '<mark>$1</mark>');
    }
}
});

1 个答案:

答案 0 :(得分:2)

而不是试图直接在正则表达式中使用变量:

$('body :not(textarea)').replaceText( /\bsplited[q]\b/gi, '<mark>$1</mark>');

你需要从字符串构造正则表达式,如下所示:

$('body :not(textarea)').replaceText(new RegExp("\\b("+splited[q]+")\\b","gi"),'<mark>$1</mark>');

还有一些其他问题,例如阵列上的for...in循环,总体上你希望它看起来像这样:

$(document).ready(function ( ) {
    if(window.querywords !== undefined){
        var qw = window.querywords.replace('%20','+');
        qw = qw.replace(' ','+');
        var splited = qw.split("+");
        for(var q=0; q<splited.length; q++){
            $('body :not(textarea)').replaceText(new RegExp("\\b("+splited[q]+")\\b","gi"),'<mark>$1</mark>');
        }
    }
});

或者,更紧凑:

$(function() {
  if(window.querywords === undefined) return;
  var qw = window.querywords.replace(/%20| /,'+').split("+");
  for(var q=0; q<qw.length; q++){
    $('body :not(textarea)').replaceText(new RegExp("\\b("+qw[q]+")\\b","gi"),'<mark>$1</mark>');
  }
});

You can test it out here