问题
<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>
回答1:
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.
来源:https://stackoverflow.com/questions/10355747/onclick-event-why-javascript-runs-it-onload