【发布时间】:2022-12-31 22:55:07
【问题描述】:
文档中加载的脚本不适用于使用 innerHTML 注入的代码。我试图放置异步或延迟但没有任何反应。
...
<script src="../scripts/traffic-lights.js"></script>
<script src="../scripts/resizeable-windows.js"></script>
<script src="../scripts/draggable-windows.js"></script>
<script>
const app = document.getElementById('app');
app.addEventListener("click", function() {addWindow("./app.html", "AppName")});
function addWindow(location, name) {
const windows = document.createElement('section');
windows.id = "window";
windows.innerHTML = `
<div class="header" id="header">
<div class="traffic-lights" id="traffic-lights">
<button class="red" id="red"></button>
<button class="yellow" id="yellow"></button>
<button class="green" id="green"></button>
</div>
<div id="movable">
<div class="appname">${name}</div>
</div>
</div>
<iframe src=${location} width= "100%" height="100%" style="border:none;"></iframe>`
document.body.appendChild(windows);
}
</script>
这是下面脚本的代码:
- resizeable-windows.js
element = document.getElementById("window");
makeResizable(element, 400, 225, 10);
...
- 可拖动-windows.js
dragElement(document.getElementById("window"));
function dragElement(element) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById("movable")) {
// if present, the header is where you move the DIV from:
document.getElementById("movable").onmousedown = dragMouseDown;
} else {
// otherwise, move the DIV from anywhere inside the DIV:
element.onmousedown = dragMouseDown;
}
...
- 交通灯.js
let trafficLights = document.getElementById("traffic-lights");
let redButton = document.getElementById("red");
let yellowButton = document.getElementById("yellow");
let greenButton = document.getElementById("green");
let windows = document.getElementById("window");
trafficLights.onmouseenter = function () { ...
【问题讨论】:
-
您需要一个文档级事件处理程序来捕获在声明处理程序之后添加的动态添加的元素。在 jquery 中,$(document).on('click', '#mynewelement', function() {/*do stuff*/});
-
好的,如果不需要 jQuery,您将如何处理?我想用 Vanilla JavaScript 完成我的项目,然后用 jQuery 更新它。
标签: javascript html css resize draggable