我试图简单地检测到单击A链接以显示警告框。每当我将脚本放在php文件中我找到一个链接时,它工作正常,但每当我把它放在我的自定义JS文件中时,它都没有检测到它,我得到错误' Uncaught TypeError :无法设置属性" onclick" null'。
php页面和自定义js页面之间的链接肯定有效,因为我在页面上有以前的工作代码。它根本不会检测到它位于外部脚本中的A链接。
HTML
<a id="ConfirmHolidayClose" href="#">
<img src="assets/img/close-button.png" alt="Holiday-request-close-button"
class="CloseButton" />
</a>
JAVASCRIPT
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
更新 - 忘记提及抱歉,我的链接嵌套在div中,名为&#39; ConfirmHoliday&#39;。
我有JS代码操作我的自定义JS中的ConfirmHoliday div,因此它无法加载,因为它现在正在很好地找到它的父div。
答案 0 :(得分:0)
javascript文件在元素创建之前运行,因此它不存在。要解决这个问题,您有两个选择:
1)使用window.onload
函数
window.onload = function () {
// Your code here
};
2)将它放在一个单独的js文件中,并在脚本标记中添加一个defer属性。
<script src="yourScript.js" defer="defer"></script>
3)将脚本标记放在锚标记
之后答案 1 :(得分:0)
它试图在它存在之前访问ConfirmHolidayClose元素吗?您的JS在页面中加载了哪里?我在猜你的<head>
一些解决方案:
1)将您的脚本移到</body>
2)将你的JS包装在dom ready函数中,这确保在DOM树存在之前不会运行JS。使用jQuery最简单,例如下面......
jQuery示例
$(function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});
Vanilla示例
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});