[英]Javascript passing argument to function that is a callback
I have a function that accepts an argument called buttonID that I need to get passed to multiple other functions. 我有一个函数接受一个名为buttonID的参数,我需要将该参数传递给其他多个函数。 When the link is clicked the ID is passed along.
单击该链接时,将传递ID。
<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. 我遇到的问题是我无法将buttonID传递给回调函数getUserInfo。
I have tried getUserInfo(buttonID) but it does not function correctly. 我已经尝试过getUserInfo(buttonID),但是它无法正常运行。 Should I be using the following syntax of getUserInfo({buttonID]) ?
我应该使用以下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. 简而言之,我需要将buttonID的值从一个函数传递到另一个函数,并且我相信正是这种语法使我受挫。 Any ideas or suggestions on what I could try differently?
关于我可以尝试不同方法的任何想法或建议吗?
You can use bind
: 您可以使用
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 更多信息: https : //developer.mozilla.org/zh-CN/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: 使用JavaScript ES6语法,要短一些:
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`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.