我想将选择框值和文本转换为对象,以下是我尝试过的。结果不是我想要的,有什么想法吗?
谢谢
HTML 代码:
<select id="district">
<option selected="" value="-1"> All </ option>
<option value="44"> Kowloon Tong </ option>
<option value="46"> Yau Yat Tsuen </ option>
<option value="47"> Ho Man Tin </ option>
<option value="101"> Fei Ngo Shan </ option>
<option value="133"> Beacon Hill </ option>
</ select>
JS代码:
var a = []
$('#district option').each(function () {
var a1 = parseInt($(this).attr('value'))
var a2 = $(this).text()
var b = {
a1: a2
}
a.push(b)
})
console.log(a)
结果:
[
Object {
a1 = " all regions "
},
Object {
a1 = " Kowloon Tong "
},
Object {
a1 = " Yau Yat Chuen "
},
Object {
a1 = " Ho Man "
},
Object {
a1 = " Fei Ngo Shan "
},
Object {
a1 = " Beacon Hill "
}
]
预期结果:
[
Object {
44 = " all regions "
},
Object {
46 = " Kowloon Tong "
},
Object {
47 = " Yau Yat Chuen "
},
...
]
最佳答案
var a = []
$('#district option').each(function () {
var a1 = parseInt($(this).attr('value'))
var a2 = $(this).text()
var b = {};
b[a1] = a2
a.push(b)
})
console.log(a)
关于javascript - jQuery:将选择框值和文本转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17036378/