I have a function that accepts an argument called buttonID that I need to get passed to multiple other functions. When the link is clicked the ID is passed along.
<a href="#" class="theme_btn" id="check-user" onClick="javascript:checkUser(this.id);">User Check</a>
My function is
function checkUser(buttonID) {
//do some stuff
var data = {};
data.callback = getUserInfo;
data.username = uname;
data.level = lvl;
checkLevel(data);
}
The problem I am having is that I am unable to pass buttonID to the callback function, getUserInfo.
I have tried getUserInfo(buttonID) but it does not function correctly. Should I be using the following syntax of getUserInfo({buttonID]) ?
In short, I need the value of buttonID to be passed from function to function and I believe it's the syntax that is holding me back. Any ideas or suggestions on what I could try differently?
You can use bind
:
function checkUser(buttonID) {
//do some stuff
var data = {};
data.callback = getUserInfo.bind(null, buttonID);
data.username = uname;
data.level = lvl;
checkLevel(data);
}
more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
You could do it with an anonymous function:
data.callback = function(){getUserInfo(buttonID)}
With the JavaScript ES6 syntax, a bit shorter:
data.callback = _=>{getUserInfo(buttonID)}
var buttonIDGlobal; function checkUser(buttonID) { buttonIDGlobal = buttonID; //do some stuff var data = {}; data.callback = getUserInfo; data.username = uname; data.level = lvl; checkLevel(data); }
You can simple define a global variable and assign the button ID to that variable. Now "buttonIDGlobal" is accessible in "getUserInfo()" function.`enter code here`
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.