简体   繁体   中英

What is the best way to call multiple functions from an onclick in Javascript

So I have an object that contained a bunch of functions. I'd like to be able to get a bunch of these functions to fire on click of just one function. I've got it working but I don't think I have the best solution. Here's my code:

HTML

<button onclick="_this.call(_this.func1(), _this.func2())">click me</button>

JS:

var _this = {};

_this.func1 = function() {
  console.log('func1');
};

_this.func2 = function() {
  console.log('func2');
};

_this.call = function() {};

edit

My main objective is to only fire certain functions at a time so I will probably have to look at using the arguments variable in the function to fire the functions.

The cleanest way is to keep html with the least JS (or better no JS at all).

So here it would be

<button id="myButton" onclick="_this.handleOnClick())">click me</button>

In JS:

var _this = {};

_this.handleOnClick = function() {
    _this.func1();
    _this.func2();
}

_this.func1 = function() {
  console.log('func1');
};

_this.func2 = function() {
  console.log('func2');
};

_this.call = function() {};

And better

document.getElementById("myButton").addEventListener("click", function(){
    _this.handleOnClick()
});

What about this one.

function one() {};
function two() {};
function three() {};

var button.document.getElementsByTagName('button')[0];

button.addEventListener('click', function() {
   one();
   two();
   three();
, false);

You can call all object methods this way:

var obj = {
    func1: function() { console.log('func1'); },
    func2: function() { console.log('func2'); }
}

Object.keys(obj).forEach(function(key){ obj[key](); }, this);

ES2015 version:

var obj = {
    func1: () => console.log('func1'),
    func2: () => console.log('func2')
}

Object.keys(obj).forEach(key => obj[key]());

obj must contain methods only

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