我需要在多个HTML文件中导入一个js文件。但是,在那种情况下,我无法在某些HTML文件中获取dom并绑定事件。
a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>a</title>
<body>
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
b.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>b</title>
<body>
<button id="btn">button</button>
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
bundle.js
const btn = document.querySelector('#btn');
btn.addEventListener('click',function(){
//...
}
console.log('a')
像这样,当我运行a.html时,会出现错误“无法读取null的属性'addEventListener'”。 这种方法可行吗?我应该如何改善?