gpt4 book ai didi

javascript - 将 HTML 片段分配给 JS 变量

转载 作者:行者123 更新时间:2023-12-03 04:55:20 24 4
gpt4 key购买 nike

我有一个 example.html 文件:

<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 函数更优雅的方式来插入属性。

最佳答案

编写 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!'))
}
})

})

关于javascript - 将 HTML 片段分配给 JS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42458831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com