【发布时间】:2021-01-13 19:40:56
【问题描述】:
我在一个文件中有一个包含 CSS、javascript 和 HTML 的表单。当用户单击按钮时,我想将文件的内容加载到我的页面中,以便用户可以完成表单。我想这样做是为了保存数据,因为我的用户可能只有 5% 的时间会使用它。
我有一个调用文件并将其加载的获取请求。
fetch('../templates/form.php/',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body:JSON.stringify({form:true}),
})
.then(resp => resp.text())
.then(response => {
document.querySelector('body').insertAdjacentHTML('beforeend',response);
})
.catch(function(error){ console.log(error); });
HTML 文件(简体)
<style>
#form{
height:100%;
width:100%;
position: absolute;
}
#submit{
width:60px;
height:30px;
}
</style>
<div>
<script>
window.addEventListener("load", function() {
document.getElementById("submit").addEventListener("click", function() {
console.log('form submitted');
});
});
</script>
<form id="form">
<input name="company-name">
<button id="submit"></button>
</form>
</div>
当我使用 fetch 请求加载文件时,它运行良好,加载了表单,并应用了 CSS。但我无法让 onclick 效果起作用。如果我将console.log() 放在提交按钮上的onclick="" 内,它就可以工作。我怎样才能让javascript工作?将 javascript 放在元素中的 onlcick 函数中是不切实际的。我正在寻找一种可以在同一个文件中使用所有 3 种数据类型的解决方案。
任何很棒的想法,谢谢
【问题讨论】:
-
不完全是,这个答案解释了如何添加完全加载的某种类型的文件。我希望插入具有所有 3 种数据类型的整个文件并让它们运行。 html a 和 css 工作文件。寻找一种让 JS 运行的方法。要么触发它,要么强制 DOM 识别它
-
stackoverflow.com/questions/2592092/… 有方法如何在使用 innerHTML 时解决它,可能适用于此。
-
感谢 cBro,在那里找到了一个有效的方法。
标签: javascript html css fetch