Javascript ~ assign variable as array index by Object

var spans = document.getElementsByTagName('span');
var input = document.getElementsByTagName('input');

var x = new Object;
x['span'] = new Object;
x['input'] = new Object;
x['radio'] = new Object;

for (var i = 0; i < spans.length; i++){
x['span'][spans[i].id] = spans[i].innerHTML;
}
for (var i = 0; i < inputs.length; i++){
if(inputs[i].getAttribute('type') == 'radio')
{
x['radio'][inputs[i].id] = inputs[i].checked;
}
else
{
x['input'][inputs[i].id] = inputs[i].value;
}
}


以上的範例會將文件中標籤為span跟input物件~~~中的id

寫成一個key到x

所以~
文件裡所有span的id都會變成x['span'][span的id] = span的id的innerHTML
文件裡所有input的id都會變成x['span'][input的id] = input的id的value
文件裡所有input中type為radio的id都會變成x['radio'][input的id] = input的id的checked

這是為了要作一個儲存的功能........所以我通通寫到一個物件

把他輸出成JSON~~~

Object.toJSON(x);

這段程式碼會輸出一堆@#$%#$^$$%&$&裡面是JSON格式

長得大概像這樣
{"span": {"b_f5_span1": "0.0000004", "b_f8_span1": "0.046", "b_f9_span1": "530000000", "b_f9_span2": "24380000", "b_f10_span1": "24380000", "b_f10_span2": "5"}, "input": {"b_f4_i1_1": "12", "b_f4_i2_1": "312", "b_f4_i3_1": "123", "b_f4_i1_2": "123", "b_f4_i2_2": "12", "b_f4_i3_2": "213", "b_f4_i1_3": "123", "b_f4_i2_3": "123", "b_f4_i3_3": "12", "b_f4_i1_4": "213", "b_f4_i2_4": "213", "b_f4_i3_4": "12", "b_f5_i1": "", "b_f9_i1": "212"}, "select": {"b_f5_s": "0.0000004", "b_f6_s": "2", "b_f7_s1": "1", "b_f7_s2": "0"}, "radio": {"b_f1_r1": true, "b_f1_r2": false, "b_f2_r1": true, "b_f2_r2": false, "b_f2_r3": false, "b_f2_r4": true, "b_f3_r1": true, "b_f3_r2": false, "b_f3_r3": true, "b_f3_r4": false, "b_f3_r5": true, "b_f3_r6": false, "b_f7_r1": false, "b_f7_r2": true}}


我打算把這一整串JSON直接當TEXT存到SQL...........這是儲存的功能

遇到讀取的時候勒~~~~~~~直接讀出來~~~把他eval~~XD

var x = eval(xxx);

這樣x就可以讀到之前的變數了~


要感謝張睪@@

因為我上網找.........找類似array named 的東西~~~~像PHP直接寫$xx['xxx']就有了

javascript不行~~~~~他就跟我說Object[str] = bitty.................我就用出來了XD

沒有留言: