最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论
<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.

发布评论

评论列表(0)

  1. 暂无评论