2011-10-04 53 views
2

我能想出如何处理jQuery替换是将特定文本替换为特定文本。 不幸的是,我无法用变量来做到这一点。jQuery - 用变量值替换文本中的单词

这是什么,我试图做一个例子:

$("#id").html($("#id").html().replace(/myVariableHere/g, 'hello')); 

myVariableHere - 这是我想提出一个变量。如果我在那里硬编码文本,一切正常。但是,由于这个值是动态的(取决于你点击的是什么),我必须在那里放置一个变量,而不是硬编码的字... 我的语法有什么问题?

在此先感谢! :)

+0

实际上,replace()与jQuery无关,它是纯粹的javascript,但仍然是一个很好的问题 – ZolaKt

回答

2

RegExp对象,而不是字面形式:

var patt=new RegExp(myVariableHere,'g'); 
$("#id").html($("#id").html().replace(patt, 'hello')); 
0

为什么要使用的正则表达式呢?

$("#id").html($("#id").html().replace(myVariableHere, 'hello')); 
0

注意,当你做对的元素的HTML内容的替换(这是什么.html()回报/套),你实际上取代了HTML代码,包括标签名称,类等因此,如果您要替换的文本恰好是HTML标记或类名,则可能会破坏文档。为了避免这种情况,遍历父元素的子节点,只有做文本节点替换:

function replaceText($elem, text, replacement) { 
    // Check if the element has just one child, and the child is a text node 
    if ($elem[0].childNodes.length == 1 && $elem[0].firstChild.nodeType == 3) 
     $elem.text($elem.text().replace(text, replacement)); 
    else 
     // Call the replacement function on each child element 
     $elem.children().each(function() { 
      replaceText($(this), text, replacement); 
     }); 
} 
0

我用下面的代码片段

$(this).text($(this).text().replace(old_word, new_word)); 

与$(这)是包含对象你想要替换的文字