将onclick事件附加到元素不起作用
Attaching onclick event to element is not working
我刚开始学习Javascript,几乎一无所知。我正在尝试将onclick事件附加到HTML中的一个元素。
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
到目前为止,这是我的代码。当ID为header的元素被点击时,什么都没有发生。我做错了什么?
下面是我的HTML代码
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<script src="testing.js"></script>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
</body>
</html>
问题是,您试图加载一个html元素,但在执行javascript函数时,该元素并不"存在",因为dom尚未完成加载。要使您的代码工作,您可以尝试以下解决方案:
将您的脚本标记放在下面的HTML:中
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
<script src="testing.js"></script>
</body>
</html>
添加一个事件处理程序来检查窗口元素是否准备好:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
}
另一种解决方案是使用jquery框架和相关的文档就绪功能http://api.jquery.com/ready/
我认为您正在寻找的解决方案是
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);
您的代码看起来很直接,可能您的脚本在DOM完全加载之前就已经运行了。为了在所有浏览器中保持简单,我们可以在末尾放置一个自执行的匿名函数,以便在加载DOM后启动所有脚本。
<html>
<title></title>
<head></head>
<body>
html here!!
<script>
(function() {
//Any other scripts here
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
})();
</script>
</body>
</html>
上面的内容纯粹是javascript,不要与jquery"document onready"函数的简写(见下文)混淆(您需要将jquery添加到页面中)。
$(function() {
//your javascript code here
});
为什么要使用自执行功能?
相关文章:
- iframe中的jQuery查找元素不起作用
- jQuery选择ajax调用中附加的元素不起作用
- 我的ID获取元素不起作用
- 为什么从 Angular 服务中的对象中删除此元素不起作用
- 将onclick事件附加到元素不起作用
- <标题>插入SVG的元素不起作用
- 使用next()的jQuery目标元素不起作用
- HTML输入元素不起作用
- 使用css显示和隐藏元素不起作用
- 焦点到 DOM 元素不起作用
- Jquery 在图像错误上对多个元素不起作用
- 按类名获取元素不起作用
- jQuery - 'addClass' to HTML 元素 - 不起作用,但在 Chrome 中正确显
- 具有 ID AND 类的 jQuery 选择器目标元素不起作用
- Ajax 对 xml 页面的响应以获取标题元素不起作用
- 单击新 DOM 元素不起作用的事件
- Javascript 添加的动态 svg 元素不起作用
- jQuery on handler 对插入的元素不起作用
- 从表单中删除添加的元素不起作用
- 相对于另一个元素的位置元素不起作用