简化的 HTML(这是一个很长的列表):
<select id="tz" name="tz">
<option timeZoneId="30" useDaylightTime="1" value="0">(GMT+00:00) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London</option>
<option timeZoneId="1" useDaylightTime="0" value="-12">(GMT-12:00) International Date Line West</option>
<option timeZoneId="2" useDaylightTime="0" value="-11">(GMT-11:00) Midway Island, Samoa</option>
</select>
对于每个时区,我都有一个值范围。我希望将每个值保存到隐藏的表单条目,因为我想保存时区,无论它们是否使用夏令时以及可能的国家/城市指示器和时间偏移 - 四件事。
隐藏表单条目(现在可见):
<input type="text" name="timeZone" id="timeZone" placeholder="Time Zone">
<input type="text" name="offset" id="offset" placeholder="Time offset">
我可以使用以下代码获取一个值(voffset):
<script>
document.getElementById("tz").addEventListener('input',MessageUpdate);
function MessageUpdate() {
vtimeZone = tz.options[tz.selectedIndex].timeZoneId;
voffset = tz.options[tz.selectedIndex].value;
// go plant recEmail and proEmail into hidden fields
var mymodal = $('#updateModalt');
mymodal.find('.modal-body input#timeZone').val(vtimeZone);
mymodal.find('.modal-body input#offset').val(voffset);
}
</script>
我尝试了各种变体来获取 timeZoneId 但无济于事。两者 value('timeZoneId') attr('timeZoneId').
总而言之,这是可行的:
voffset = tz.options[tz.selectedIndex].value;
我觉得我很接近,因为这不会产生任何值(value),也不会产生错误:
vtimeZone = tz.options[tz.selectedIndex].timeZoneId;
最佳答案
你在这里猜测了一点。
首先,没有错误,因为您所做的只是调用未定义的属性。在 JavaScript 中,这不会产生错误。
其次,val('timeZoneId')
(假设您的意思是这个,而不是 value()
,它不是 native 或 jQuery 方法)将设置 value
属性,而不检索任何内容(属性、值或其他。Docs .)
首先,更改 HTML 以使用数据属性。
<option
data-timeZoneId="30"
data-useDaylightTime="1"
value="0"
>
(GMT+00:00) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London
</option>
然后在你的 JS 中通过 getAttribute()
引用它们:
document.querySelector('#tz').addEventListener('input', evt => {
let
opt = evt.target.options[evt.target.selectedIndex],
vtimeZone = opt.getAttribute('data-timeZoneID'), // <--
voffset = opt.value;
;
//etc...
});
关于javascript - 选择选项多值提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51234297/