gpt4 book ai didi

javascript - 在 jQuery select 中获取未定义的值

转载 作者:行者123 更新时间:2023-11-30 15:53:54 24 4
gpt4 key购买 nike

我需要从选择的 HTML 中获取一个值,以便与整数值进行比较并采取一个或另一个操作。问题是我总是从 select 中得到 undefined 值,然后我无法将 undefined 与 Integer 进行比较,谢谢。

代码:

var toRet
$(document).ready(function(){
$('#id_event_type').on('change', function() {
toRet = $('#id_event_type :selected').val(); //:selected is not necesary I think
alert($(toRet).val());//returns undefined

});
});
if (toRet == 2){
var eventIcon = new OpenLayers.Icon('/stati/img/accidente.png',eventSize, eventOffset);
}
if (toRet == 0){
var eventIcon = new OpenLayers.Icon('/static/img/obrasMarker.png', eventSize, eventOffset);
}
if (toRet == 1){
var eventIcon = new OpenLayers.Icon('/static/img/alertMarker.png', eventSize, eventOffset);
}
if (toRet == ""){
var eventIcon = new OpenLayers.Icon('/static/img/alertMarker.png', eventSize, eventOffset);
}
eventMarkerslayer.addMarker(new OpenLayers.Marker(eventPosition, eventIcon));

代码更新:

toRet = null;
//var selector = document.getElementById("id_event_type")
//var valorSeleccionado = selector.options[selector.selectedIndex].value;
$(document).ready(function(){
slc = $('#id_event_type');

slc.on('change', function(){

toRet = parseInt(slc.find(":selected").val(), 10);//here is ok!

});
//from here toRet is null
if (toRet == 2){
var eventIcon = new OpenLayers.Icon('/static/img/accidente.png', eventSize, eventOffset);
}
if (toRet == 0){
var eventIcon = new OpenLayers.Icon('/static/img/obrasMarker.png', eventSize, eventOffset);
}
if (toRet == 1){
var eventIcon = new OpenLayers.Icon('/static/img/atascoMarker.png', eventSize, eventOffset);
}

eventMarkerslayer.addMarker(new OpenLayers.Marker(eventPosition, eventIcon));
eventMarkerslayer.setVisibility(false);
$( "#visibilityEvents" ).change(function() {
if ($('#visibilityEvents').is(":checked")) {
eventMarkerslayer.setVisibility(true);
} else {
eventMarkerslayer.setVisibility(false);
}
});
});

HTML:

<select id="id_event_type" name="event_type" required="">
<option value="" selected="selected">---------</option>
<option value="0">Obras en la carretera</option>
<option value="1">Congestion del trafico</option>
<option value="2">Accidente</option>
</select>

最佳答案

试试这个

$(document).ready(function(){
var slc = $('#id_event_type');

var value;

slc.on('change', function(){
value = slc.find(":selected").val();
alert(value);
})

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="id_event_type" name="event_type" required="">
<option value="" selected="selected">---------</option>
<option value="0">Obras en la carretera</option>
<option value="1">Congestion del trafico</option>
<option value="2">Accidente</option>
</select>

关于javascript - 在 jQuery select 中获取未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38888836/

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