简体   繁体   中英

Global variables in javascript not working?

I have two functions in JavaScript. One is change_BASE_ID() and the other one is Display_img(a,b) .

change_BASE_ID() is called on mouseclick and internally calls Display_img() . On mouseover, Display_img() is called.

So Display_img() is used in two ways. There is a base_id_mitali variable in change_BASE_ID() which I want to be global. So even on mouseover when the Display_img() function is called independently, it should make use of the value of that variable.

If the onclick function was never clicked the value in base_id_mitali should be 01 or else if it was clicked it should be the one previously set ones.

 var base_id_mitali = ""; function change_BASE_ID(base_ID, cursor_ID) { // THIS IS WHEN MOUSE IS CLICKED //var curr_base_id = 'ch01ch01.png'; var start_name = "ch"; base_id_mitali = "01"; var bsid = document.getElementById('image').src; //var bsidlen=bsid.charAt(bsid.length-6); var bid1 = bsid.charAt(bsid.length - 6); var bid2 = bsid.charAt(bsid.length - 5); document.getElementById("mitali").innerHTML = "trying to get base id ".concat(bid1).concat(bid2); base_id_mitali = concat(bid1).concat(bid2); var a = base_ID; var b = cursor_ID; var temp_res1 = start_name.concat(base_id_mitali); var temp_res2 = temp_res1.concat("ch"); var temp_res3 = temp_res2.concat(b); var final = temp_res3.concat(".png"); curr_base_id = final; document.getElementById('image').src = final; Display_img(base_ID, cursor_ID); document.getElementById("demo").innerHTML = "clicked on ".concat(final); //setbaseid(base_id_mitali); } function Display_img(a, b) { var start_name = "ch"; //document.getElementById("globalvar").innerHTML = "trying see global variable value ".concat(base_id_mitali); var temp_res1 = start_name.concat(a); //want to use the global variable instead of a var temp_res2 = temp_res1.concat("ch"); var temp_res3 = temp_res2.concat(b); var final = temp_res3.concat(".png"); document.getElementById("demo").innerHTML = final; document.getElementById('image').src = final; } 

I cannot see any initialization for the variable base_id_mitali in the code. Outside of your html code, initialize the variable on load using following code :

<script>
var base_id_mitali= "";
</script.

Now you can access this global variable .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM