简体   繁体   中英

Executing Commands Javascript

I want to execute a command by the click of a button, and not when the page loads.

function hey() {
  alert('bla');
}

Do I add something to the code above or to the button?

<input type="button" value="Click Me" onclick="hey()" />

Have you taken the time to type in your question into the magical Google box yet? Surely you'll see something like this:

<input type="button" value="Click me, now" onclick="hey()" />

Say you have the function that alerts a window to the user.

<script type="text/javascript">
    function showMe() {
        alert('You clicked on the button');
    }
</script>

<button onclick="showMe()">Button</button>

This will make sure that the function is only called when the button is clicked upon and not when the page is loaded.

Okay, so you have a code that should work for alerting something on the click of a button. But you state that the code is running on page load. You have to check you code, looking for:

  • An onload attribute on the body tag, something like <body onload="hey()">
  • A call to hey somewhere else on your js code. Look for hey() .
  • Maybe a reference to the button followed by a call to .click()

There is something else on your code causing the function to be called, you'll have to scan your code to find out what it is.

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