<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
1 Answer
Reset to default 5This 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条)