I am trying to programmatically create links which will, when a link is clicked, set a variable. This variable will be used to load a profile.
Here's the code (with console.logs added in):
var link = document.createElement("a");
link.innerHTML = user.Name;
link.setAttribute("data-role", "button");
link.setAttribute("href", "#page-profile");
var UID = user.UID;
console.log(UID);
link.onclick = function(UID) {
console.log(UID);
var profile = UID;
}
However I'm not quite sure how to pass the variable along to the onclick at runtime.
How do I get a value from a link to a Javascript variable?
This is for a PhoneGap application if that helps.
Edit, as apparently some people feel the question is unclear:
I want to, upon clicking a link, set a variable value based on another variable I have. That's it.
you can set the value of a data attribute for the link, like:
link.setAttribute("data-id", user.UID);
link.onclick = function(e) {
var profile = this.dataset.id;
};
A closure is an inner function that has access to the outer (enclosing) function's variables—scope chain
So do not define UID as a function argument! your function argument is the (click)event in that case!
See my JS Fiddle. (I set static values for the user vars for testing)
https://jsfiddle.net/87jthdpt/1/
Example of the closure
var UID = "test";
link.onclick = function(ev) {
console.log(UID);
var profile = UID;
}
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.