简体   繁体   中英

Javascript (no Jquery): How do I call a function on click?

After looking through all the JS docs out there, I just can't figure out why this isn't working: I've got a button with the ID of "next", and all I wanna do is trigger the function whenever the user clicks on that button.

    var nextBtn = document.getElementById("next");

    var nextSlide = function (a,b){
        return a + b;
    }

    nextBtn.onclick = nextSlide(4,5);

So when the user clicks on the button, I can see the "9" in the console.

You can use an anonymous function expression like this:

HTML

<button id="next">next button</button>

Javascript

var nextBtn = document.getElementById("next");

var nextSlide = function (a,b){
    console.log(a + b); // for display purpose only
    return a + b;
}

nextBtn.onclick = function(){
  nextSlide(4,5);
} 

PLAYGROUND

Use

window.onload=function(){
var nextSlide = function (){
                 this.add=function(a,b){
                        console.log(a+b);
                     return a+b;
                  };
                 };
var nextBtn= document.getElementById('btn');
 //nextBtn.attachEvent('onclick', new nextSlide().add(4,5)); //With versions less than IE9
 nextBtn.addEventListener('click',new nextSlide().add(4,5), false); //IE9 and above
 };

You can say like this

var nextSlide = function (a, b){
  return function(){
     return a+b;
  }
}
var nextBtn = document.getElementById("next");
nextBtn.onclick = nextSlide(4,5);    // so basically the clicking on button will call the function being returned by function nextSlide.

用这个:

nextBtn.onclick = function() { nextSlide(4,5); }

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