//js:
fetch('http://localhost:8000/cors', { // 目前的端口号是5000,也是localhost,跨域端口号是8000 mode: 'cors' }) .then(res => res.text()) .then(data => { console.log(data); document.body.innerHTML += data; }) .then(err => console.log(err));//取到的HTML片段
<input type="button" value="create p movement">
<style>
input{
border: 1px solid #ddd;
padding: 5px 10px;
background-color: palevioletred;
border-radius: 5px;
outline: none;
box-shadow: 2px 3px 10px rgba(0,0,0,.3);
}
.box{
width: 100px;
height: 100px;
background-color: mediumvioletred;
animation: change 2s linear alternate;
}
@keyframes change{
0%{
transform: translate(0,0);
}
30%{
transform: translate(100px,0);
}
60%{
transform: translate(100px,200px);
}
100%{
transform: translate(0,0);
}
}
</style>
<script src="../js/cors.js"></script>
//cors.js
let btn = document.querySelector('input[type=button]');
btn.onclick = function () {
let p = document.createElement('p');
p.classList.add('box');
document.body.append(p);
console.log(p)
};
页面样式和DOM结构出来了,但是js却不生效,有什么办法还原获取到的html原本的js吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
浏览器的安全策略限制,innerHTML 中的script是不会执行的。
你需要手动把script标签分离出来,单独createElement一个script出来。
试试innerHtml后加个这个