function - onclick event - why Javascript runs it onload - Stack Overflow

<p id="specialp">some content<p><script>document.getElementById('sp

<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>
<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>
Share Improve this question edited Sep 15, 2019 at 18:33 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 27, 2012 at 18:10 AtheusAtheus 941 silver badge7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744372242a4571012.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信