onclick事件 - 为什么JavaScript运行它onload [英] onclick event - why javascript runs it onload
问题描述
< p id =specialp>某些内容< / p>
< script>
document.getElementById('specialp')。onclick = alert('clicked');
< / script>
我刚刚开始使用javascript,并且我不明白为什么在执行警报时页面加载,但不是当我点击该段落。
$ b 处理程序按我期望的方式工作,如下图所示:
< p id =specialponclick =alert('clicked')>某些内容< / p>
这是因为您没有将 onclick
赋值作为一个实际的函数,所以它试图将 alert('clicked')
的结果赋值给onclick事件处理函数意味着它可能在分配时是 undefined
)。你需要做的是将一个函数分配给该处理程序,如下所示:
document.getElementById('specialp')。onclick =函数()
{
alert('clicked');
};
当您在HTML中执行相同的操作时,DOM会自动将该内容封装在一个函数中。
<p id="specialp">some content</p>
<script>
document.getElementById('specialp').onclick=alert('clicked');
</script>
I'm just starting out with javascript, and I don't understand why the alert is executed when page loads, but not when I click that paragraph.
The handler works as I expect when I put it inline, like this:
<p id="specialp" onclick="alert('clicked')" >some content</p>
This is because you didnt wrap the onclick
assignment as an actual function, so it attempts to assign the result of alert('clicked')
to the onclick event handler (which means it's probably undefined
when assigned). What you need to do is assign a function to that handler like so:
document.getElementById('specialp').onclick = function()
{
alert('clicked');
};
When you do the same thing in HTML, the DOM automatically wraps that content in a function for you.
这篇关于onclick事件 - 为什么JavaScript运行它onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!