Reputation: 91
So here is a dumbed down version of what I'm doing. I want to change the onclick for a span to call a function with a variable as its argument. I want it to use the variable as it exists when I create the new onclick not as the variable is at the time of the click.
<html>
<head>
<script>
function share(it) {
alert("We wanted 1, we got "+ it);
}
</script>
</head>
<body>
<span id="key">Click me</span>
<script>
var x = 1;
document.getElementById('key').onclick = function() {share(x)}
x++;
</script>
</body>
</htmL>
Upvotes: 0
Views: 139
Reputation:
All you need to do is just declare the variable in the head. The variable is user-defined and hard coded, so it can load in the head and then just refer to it in the function when the click happens. You don't need to pass a parameter
Upvotes: 0
Reputation: 798
Don't use a function() directly, use a function that creates the onclick function:
<html>
<head>
<script>
function share(it) {
alert("We wanted 1, we got "+ it);
}
function makeFunction(x) {
return function() {share(x);}
}
</script>
</head>
<body>
<span id="key">Click me</span>
<script>
var x = 1;
document.getElementById('key').onclick = makeFunction(x)
x++;
</script>
</body>
</html>
Upvotes: 1
Reputation: 18292
I think you need this:
<html>
<head>
<script>
function share(it) {
alert("We wanted 1, we got "+ it);
}
</script>
</head>
<body>
<span id="key">Click me</span>
<script>
function assign(y) {
return function() { share(y); };
}
var x = 1;
document.getElementById('key').onclick = assign(x);
x++;
</script>
</body>
</html>
Upvotes: 1
Reputation: 462
make a copy of x and pass that to the function
<html>
<head>
<script>
function share(it) {
alert("We wanted 1, we got "+ it);
}
</script>
</head>
<body>
<span id="key">Click me</span>
<script>
var x = 1;
var copyOfx = x + 0;
document.getElementById('key').onclick = function() {share(copyOfx)}
x++;
</script>
</body>
Upvotes: 0