简体   繁体   English

将全局变量设置为javascript后访问

[英]accessing global variables after setting them javascript

在此处输入图片说明

I am trying to keep track of changes to a select box in django. 我试图跟踪对Django中选择框的更改。 My code below is working up to alert(change.new_time); 我下面的代码正在努力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. 我尝试了4-5种不同的方法,并遵循了在此站点上找到的func中的全局变量的某些规则,但无法从新数组访问任何内容。 Am I doing something wrong adding to the array? 我在添加阵列时做错了吗? I tried push too. 我也尝试过推。 Thank you 谢谢

You can use Object as associative array. 您可以将Object用作关联数组。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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