2017-02-25 48 views
0

我有一個example.html文件:分配HTML片段到JS變量

<span> 
{{test}} 
</span> 

而且一個main.js文件:

$("button#test").click(function(event) { 

     var html = '/example.html'; 

     //Replaceing {{test}} in example.html with 'Hello, World!' string 
     var insertProperty = function (string, propName, propValue) { 
      var propToReplace = "{{" + propName + "}}"; 
      string = string 
       .replace(new RegExp(propToReplace, "g"), propValue); 
      return string; 
     } 
     var replacedhtml = insertProperty(html,"test", 'Hello, World!'); 

     return console.log(replacedhtml); 
    }); 

我目前得到的日誌:

/example.html 

我預計:

<span> 
Hello, World! 
</span> 

而且應該有一個比我的insertProperty函數更優雅的插入屬性的方法。

+1

寫作'變種HTML =「/ example.html''創建一個字符串,而不是檢索從文件中的HTML文本。後者需要使用'$ .ajax'。 – gyre

+0

你爲什麼不用模板引擎如ejs,玉 –

回答

1

寫作var html = '/example.html'創建一個字符串而不是從文件中檢索html文本。相反,請使用$.ajax異步請求文件並使用其文本進行操作。

$('#test').click(function() { 
 

 
    $.ajax({ 
 
    url: '/example.html', 
 
    success: function (html) { 
 

 
     //Replacing {{test}} in example.html with 'Hello, World!' string 
 
     function insertProperty (string, propName, propValue) { 
 
     return string.replace(new RegExp('{{' + propName + '}}', 'g'), propValue) 
 
     } 
 

 
     console.log(insertProperty(html, 'test', 'Hello, World!')) 
 
    } 
 
    }) 
 

 
})

+0

謝謝,你!這有效,但看起來更像是解決方法。我是JS新手,所以我可能是錯的。 –