gpt4 book ai didi

javascript - jQuery:将选择框值和文本转换为对象

转载 作者:行者123 更新时间:2023-11-28 12:35:56 25 4
gpt4 key购买 nike

我想将选择框值和文本转换为对象,以下是我尝试过的。结果不是我想要的,有什么想法吗?

谢谢

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com