2011-10-04 50 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)); 

與$(這)是包含對象你想要替換的文字