2013-04-08 92 views
-1

控制檯給我一個錯誤,而試圖更改JavaScript模板表達的textnode的文本值即${foo}

的js

  // this.textContent here gives ${languageLabel} 
      var variable = UI.patternMatch(textNodes_elRef); 
      $(variable).nodeValue ="language"; 
     }); 


patternMatch : function(textNode) { 
    var templateRegex = /\${([\S\s]*?)\}/g; 
    return $(textNode).contents().filter(function() { 
     if($(this.textContent).match(templateRegex)){ 
      // ** How do i return the textnode with only matched pattern** 
     } 

所以總結基本上我想改變$ {languagelabel}的textnode的textValue爲語言,但我得到的錯誤爲**語法錯誤,無法識別的表達式:$ {languageLabel} **

+0

'UI.patternMatch(this.textContent)'返回什麼? – Ian 2013-04-08 00:43:08

+0

我猜'$ {languageLabel}'被傳遞給'$()',因爲當我調用'$(「$ {languageLabel}」)''時我得到了同樣的錯誤。 – Ian 2013-04-08 00:45:41

+0

另外,'.textValue'不是一個jQuery方法。您可能正在尋找'.text()'。 – Ian 2013-04-08 00:49:05

回答

1

您可以只需存儲對循環後匹配並返回的textNode實例的引用,並且不必僅使用jQuery來修改textNode的nodeValue屬性。以下是一個示例http://jsfiddle.net/LAud7/

function patternMatch(el) { 
    var templateRegex = /\${([\S\s]*?)\}/g, 
     nodeFound; 

    $(el).contents().each(function() { 
     if (templateRegex.test(this.nodeValue)) { 
      nodeFound = this; 
      return false; 
     } 
    }); 

    return nodeFound; 
} 

patternMatch($('#test')).nodeValue = 'replaced content'; 

請注意,使用這種方法,如果包含textNode${...}包含其它文字以及,它不會產生預期的結果,因爲所有的文字將被替換,所以你需要確保的是,${...}包含在它自己的textNode中。

+0

我仍然發現相同的錯誤..我通過textnode文本內容,也嘗試傳遞元素本身,但它給了我一個錯誤 – inputError 2013-04-08 13:08:12

+0

什麼'alert(typeof patternMatch(...));'return? – plalx 2013-04-08 13:29:55

+0

我終於明白了..謝謝你的建議..它的工作..我通過模式匹配的節點,並通過每個節點循環,並獲得對匹配節點的引用,並返回它,並做了一些改變,它的工作..謝謝這麼多+1 – inputError 2013-04-08 13:39:31

相關問題