我理解这个问题和大多数解决方案,但我似乎无法在一个小型应用程序测试中解决这个问题。
我试过了;包装在DOMContentLoaded中,defer脚本位于HTML主体的底部,尝试了IF语句的方法。我不明白为什么在构建DOM元素之前它仍然到达侦听器。
在本地节点v14服务器上进行测试,无法想象这会是一个问题。
有什么可能的解决方案吗?
<!DOCTYPE html>
<html>
<head>
<title>Image Compositor</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<input type="file" id="image-input" name="images" accept=".jpg, .jpeg, .png" multiple required>
<div id="preview"></div>
<button id="process-button" disabled>Process Images</button>
<div id="result"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.13.0/Sortable.min.js"></script>
<script src="script.js"defer></script>
</body>
</html>
和script.js
document.addEventListener('DOMContentLoaded', function() {
const input = document.getElementById('image-input');
const preview = document.getElementById('preview');
const processButton = document.getElementById('process-button');
const result = document.getElementById('result');
let imageUrls = [];
input.addEventListener('change', function () {
const formData = new FormData();
Array.from(input.files).forEach((file, index) => {
formData.append(`images`, file);
});
fetch('/upload', { method: 'POST', body: formData })
.then(response => response.json())
.then(data => {
imageUrls = data.urls;
preview.innerHTML = '';
imageUrls.forEach(url => {
const img = document.createElement('img');
img.src = url;
img.dataset.id = url;
preview.appendChild(img);
});
Sortable.create(preview);
processButton.disabled = false;
})
.catch(error => console.error(error));
});
processButton.addEventListener('click', function () {
const order = Array.from(preview.children).map(img => imageUrls.indexOf(img.dataset.id));
fetch('/process', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order }) })
.then(response => response.json())
.then(data => {
result.innerHTML = '';
const img = document.createElement('img');
img.src = data.url;
result.appendChild(img);
const link = document.createElement('a');
link.href = data.url;
link.download = 'composite.png';
link.textContent = 'Download image';
result.appendChild(link);
})
.catch(error => console.error(error));
});
});
错误:
script.js:6 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at script.js:6:7
谢谢
大卫
预期错误不存在:)
script.js:6 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at script.js:6:7