Home > front end >  Ask god to help optimize the js code written
Ask god to help optimize the js code written

Time:09-28

Var data1={
City: [" 1 ", "2", "3"],
Num: [" 10 ", "11", "12"]
}

Var data2={
City: [" 4 ", "5", "6"],
Num: [" 20 ", "21", "22"]
}


Var data3={
City: [" 7 ", "eight" and "9"],
Num: [" 15 ", "16" and "17"]
}


The function xuanze (sj1) {}

Xuanze (data1)

For (the let I=0; I & lt; Optionsli. Length; I++) {
Optionsli [I] index=I;
Optionsli [I] onclick=function () {
If (this. Index==0) {
Xuanze (data1)

}
If (this. Index==1) {
Xuanze (data2)
}

If (this. Index==2) {
Xuanze (data3)
}

}

}

Above is a click to load a function code, when the var date too many variables, such as data4 data5 data6 more time, one is to judge which, click on the load function, certainly not appropriate, but the function as stitching method and there is a problem, so I want to ask everybody to help optimize, how to write a more appropriate

CodePudding user response:

Online/,,,,,,,

CodePudding user response:

Optionsli [I] onclick=function () {
Xuanze (eval (" data "+ (enclosing index + 1)))
}

CodePudding user response:

 
It is best to data1 data2 data3 multiple variables instead of an array, such as
Var data=https://bbs.csdn.net/topics/[{
City: [" 1 ", "2", "3"],
Num: [" 10 ", "11", "12"]
}, {
City: [" 4 ", "5", "6"],
Num: [" 20 ", "21", "22"]
}, {
City: [" 7 ", "eight" and "9"],
Num: [" 15 ", "16" and "17"]
}];

Can directly xuanze (data [0])
In the event
Optionsli [I] onclick=function () {
Xuanze (data [this index])
}

CodePudding user response:

No way,
You should try to put the same kind of data in an array,
  • Related