RT
<select id="test"></select>
var options = [
{
key: 1,
name: 'a11111',
},
{
key: 2,
name: 'b222222',
},
{
key: 3,
name: 'c33333',
},
{
key: 4,
name: 'd4444444',
},
]
var optionHtml = ''
options.forEach(function (item) {
optionHtml += `<option value="${item.key}">${item.name}</option>`
})
$('#test').html(optionHtml)
$(function () {
setTimeout(() => {
$('#test option').each(function () {
var optionVal = $(this).val()
if (Number(optionVal) === 2) {
$(this).attr('disabled', 'disabled')
$(this).attr('selected', 'selected')
}
})
}, 1000)
setTimeout(() => {
console.log('錯誤的取值方法', $("#test").val())
console.log('正確的取值方法', $("#test option:selected").val())
}, 2000);
})