简体   繁体   中英

JS code fires on page load instead of waiting for click event

I'm having difficulty with this code. I'm trying to get the JS to execute on a click event however, it is executing when the page loads and also when the user clicks. Any help is much appreciated!

<body>
<a href="" id="calc">click me!</a>
</body>
<script type="text/javascript">
window.onload = function () {
document.getElementById('calc').onclick=xfx()
}

xfx = function (){
alert("x");
}
</script>
</body>

You are invoking the function instead of assigning it to the on click event

This should do it:

document.getElementById('calc').onclick = xfx;

The line

    document.getElementById('calc').onclick = xfx();

means that you want to assign the onclick to the results of the xfx() call.

You probably want

    document.getElementById('calc').onclick = xfx;

which means that you want to assign to onlick the xfx function itself.

I'd use addEventListener to look for the click on your variable; like so:

var clickMe = document.getElementById('calc');

clickMe.addEventListener('click', function () {
alert("hello!");
});

Where your variable is clickMe, defining the id 'calc', and when clicked it triggers the alert.

Here's the fiddle, http://jsfiddle.net/89Nvb/

Should be

function xfx() {
  alert("x");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM