Javascript .onclick = functionName passing paramet

2019-05-18 17:33发布

问题:

I have this code:

var bt = document.getElementById("bt");
bt.onclick = randomFunc;

Now, how can I pass some parameters to randomFunc?

回答1:

Create a new function which calls randomFunc and specify the parameters there.

bt.onclick = function () {
    randomFunc(foo, bar, baz);
};

Or, if you can limit support to browsers which support bind, use that method to create your function:

bt.onclick = randomFunc.bind(this, foo, bar, baz);