给元素附加onclick事件不起作用

5

我刚开始学习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>

1
对我有用。你遇到了什么错误?你是否实际拥有一个 id='header' 的元素? - MikeSmithDev
1
这里运行良好 http://jsfiddle.net/j08691/4EFv3/. 你把JavaScript放在页面的哪里了? - j08691
如果我的问题或代码不够清晰,请注意:当用户单击具有标题 ID 的元素时,警报消息应该显示。 - Andrew Dawson
什么也没有发生。HTML 加载了,但当我点击标题时,什么也没发生。 - Andrew Dawson
1
你尝试过在闭合的body标签之前加载代码吗?你需要确保不要在还不存在的元素上执行代码。 - j08691
显示剩余5条评论
3个回答

3
问题在于,当JavaScript函数被执行时,您尝试加载一个HTML元素,但该元素并不存在,因为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/

2
我认为你正在寻找的解决方案是:
var joinList = function() {
    alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);

我需要使用字符串而不是函数:span.setAttribute('onclick', 'event.stopPropagation()') - andreshg112

0

你的代码看起来很简单,但可能是因为脚本在 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的“文档就绪”函数的速记(见下文)混淆(您需要将jQuery添加到您的页面中)。
$(function() {
        //your javascript code here
});

为什么要使用自执行函数?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接