javascript - Get variable *value* instead of variable itself -
look @ code:
<button id="button">test</button> <button id="button2">test</button> <script> button = document.getelementbyid("button"); button2 = document.getelementbyid("button2"); var x = 5; button.onclick = function() { alert(x); } var x = 10; button2.onclick = function() { alert(x); } </script>
when click on both of buttons, 10
result. wanted 5
result first button. i.e, didn't want set alert parameter variable, rather actual value of variable. possible in javascript?
javascript has function scope variables. if want use same variable twice should not same reference, need put code in different scopes (functions). this:
button = document.getelementbyid("button"); button2 = document.getelementbyid("button2"); (function() { var x = 5; button.onclick = function() { alert(x); } })(); (function() { var x = 10; button2.onclick = function() { alert(x); } })();
jsfiddle: http://jsfiddle.net/q91uhvw3/
or if not want that, can force evaluation of x
@ time of creating onclick
handler first button so:
button = document.getelementbyid("button"); button2 = document.getelementbyid("button2"); var x = 5; (function(xrightnow) { button.onclick = function() { alert(xrightnow); } })(x); var x = 10; button2.onclick = function() { alert(x); }
jsfiddle: http://jsfiddle.net/q91uhvw3/2/
Comments
Post a Comment