2017-02-25 49 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新手,所以我可能是错的。 –