简体   繁体   中英

accessing global variables after setting them javascript

在此处输入图片说明

I am trying to keep track of changes to a select box in django. My code below is working up to alert(change.new_time); , so I am making the object correctly-

        var changed_select_box_array = [];


        function handleChanges(id){
            var x = document.getElementById(id).selectedIndex;
            var time = document.getElementsByTagName("option")[x].value;
            var change = {id:id, new_time:time};
            alert(change.id);
            alert(change.new_time);
            changed_select_box_array[changed_select_box_array.length] = change;
            alert(changed_select_box_array[0].id);
        }

but I cannot access the new item in the array. I tried 4-5 different ways and followed some rules for global variables in funcs I found on this site, and I cannot access anything from the new array. Am I doing something wrong adding to the array? I tried push too. Thank you

You can use Object as associative array.

 var changed_select_box_array = {}; function handleChanges() { var x = this.selectedIndex; var id = this.id; var time = this.getElementsByTagName("option")[x].value; var change = { id: id, new_time: time }; changed_select_box_array[id] = change; console.log(changed_select_box_array); } 
 <!--Emitation of some select inputs with change events--> <select id="s1" onchange="handleChanges.call(this)"> <option value="val1">Value 1</option> <option value="val2">Value 2</option> <option value="val3">Value 3</option> </select> <select id="s2" onchange="handleChanges.call(this)"> <option value="val4">Value 1</option> <option value="val5">Value 2</option> <option value="val6">Value 3</option> </select> 

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