gpt4 book ai didi

javascript - 纯js使用ajax加载html和js,但js不起作用

转载 作者:行者123 更新时间:2023-12-03 08:11:50 24 4
gpt4 key购买 nike

我想使用ajax加载html文件并执行脚本。这是我要加载的 html 文件:

<div class="panel panel-body">
<h4>Personal Data</h4>
<hr />
<span data-bind="editable: firstName"></span>
<span data-bind="text: firstName"></span>
</div>

<script>
(function () {
console.log('lala');

var viewModel = function () {
var self = this;
self.id = ko.observable();
self.firstName = ko.observable('YZ');
self.lastName = ko.observable();
self.gender = ko.observable();

self.genders = ko.observableArray();
}
var vm = new viewModel();
ko.applyBindings(vm);
})
</script>

这就是我加载和执行的方式:

Mark.load(t.pathToTemplate, t, function (htmlTemplate, path, option) {
var wrap = document.createElement('div');
wrap.innerHTML = htmlTemplate;
var scripts = wrap.getElementsByTagName('script');
if (scripts.length > 0) {
var newjs = document.createElement('script');
newjs.onreadystatechange = function () {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
cb();
}
};
newjs.onload = function () {
cb();
};
newjs.innerHTML = scripts[0].innerHTML;
document.body.appendChild(newjs);
}
document.getElementById(option.renderIn).innerHTML = htmlTemplate;

});
Mark.load = function (path, option, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', path, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText, path, option);
}
};
xobj.send(null);
}

加载和追加工作正常,但 js 未执行。如何将该 js 脚本附加或添加到文档中并使用纯 js 执行它?

最佳答案

您正在声明匿名函数,但并未执行它。您需要在函数末尾添加 () 来执行它:

<script>
(function () {
console.log('lala');

var viewModel = function () {
var self = this;
self.id = ko.observable();
self.firstName = ko.observable();
self.lastName = ko.observable();
self.gender = ko.observable();

self.genders = ko.observableArray();
}
var vm = new viewModel();
ko.applyBindings(vm);
})();
</script>

关于javascript - 纯js使用ajax加载html和js,但js不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34109508/

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