简体   繁体   中英

How to run a function on button click?

How do I run this function If I click on the button?

<button id="button">Button</button>

var tween = new TWEEN.Tween(mesh.scale).to({ x: 1, y: 0.05, z:2 }, 1000).start();


tween.easing(TWEEN.Easing.Elastic.InOut);
tween.repeat(Infinity);
tween.yoyo(true);

The onclick attribute on a button will accept a JavaScript function to call whenever it is clicked, like so:

<button id="button" type="button" onclick="functionToCall">Button</button>

<script>
  function functionToCall() {
     // ...
  }
</script>

However, it is often better to attach an eventListener to the button, like so:

<button id="button" type="button">Button</button>

<script>
    // Plain JS
    document.getElementById('button').addEventListener('click', function() {
      // ...
    });

    // jQuery
    $('#button').click(function() {
      // ...
    });
</script>

Using the onclick attribute will overwrite any previously attached listeners, and in modern applications it is common to see multiple event handlers associated with an DOM node.

Using addEventListener will ensure that the previously attached handlers remain in tact and can executed at the same time.

There is also a removeEventListener method that can be used to stop execution of a function when an event is triggered if you ever need to do something only once. In those instances, it is common to use a named function instead of an anonymous function like the one in my previous example.

document.getElementById("button").addEventListener("click", clickHandlerOnce);
function clickHandlerOnce() {
   // ...
   this.removeListener("click", clickHandlerOnce);
}

Using jQuery:

$('#button').click(function(){
   var tween = new TWEEN.Tween(mesh.scale).to({ x: 1, y: 0.05, z:2 }, 1000).start();
   tween.easing(TWEEN.Easing.Elastic.InOut);
   tween.repeat(Infinity);
   tween.yoyo(true);
   return false; //if you want the button to not process anything further
});

The problem here is that you want to be able to run your JavaScript code when you click the button. The solution to this is to create a function, then set the 'onclick' property of the button to the name of your function. Like this:

<button id="button" onclick="functionName()">Button</button>

<script>
function functionName ()
{
var tween = new TWEEN.Tween(mesh.scale).to({ x: 1, y: 0.05, z:2 }, 1000).start();
tween.easing(TWEEN.Easing.Elastic.InOut);
tween.repeat(Infinity);
tween.yoyo(true);
}
</script>

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