對于html5使用相信很多小伙伴們都知道了怎么實現(xiàn),接下來我們來說說有關(guān)于:“如何在html5實現(xiàn)datalist選中option選項的觸發(fā)事件?”這方面的相關(guān)內(nèi)容分享!
代碼如下:
<!DOCTYPE HTML>
<html>
<body>
<script src="./jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script>
<script>
function inputSelect(){
var input_select=$("#input").val();
var option_length=$("option").length;
var option_id='';
for(var i=0;i<option_length;i++){
var option_value=$("option").eq(i).attr('data-value');
if(input_select==option_value){
option_id=$("option").eq(i).attr('data-id');
break;
}
}
console.log(input_select,option_length,option_id);
};
</script>
<input list="cars" id="input" οnchange="inputSelect()"/>
<datalist id="cars">
<option value="111" data-value="111" data-id="1">
<option value="122" data-value="122" data-id="2">
<option value="1222" data-value="1222" data-id="4">
</datalist>
</body>
</html>
html5中datalist, 對選擇的option選項獲取對應(yīng)的屬性值:
<!DOCTYPE HTML>
<html>
<body>
<script src="jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
function inputSelect(){
var input_select = $("#input").val();
var after_value = input_select.split(".");
var new_value = after_value[0] + "." + after_value[1] + "." + after_value[2] + ".xxx";
$("#input").val(new_value);
var option_length = $("#netsegments").find("option").length;
var data_id = '';
var firstIp = 1;
var lastIp = 255;
for(var i = 0; i < option_length; i++){
var option_value = $("option").eq(i).attr('data-value');
if(input_select == option_value){
data_id = $("option").eq(i).attr('data-id');
firstIp = $("option").eq(i).attr('firstIp');
lastIp = $("option").eq(i).attr('lastIp');
break;
}
}
console.log("input_select:" + input_select + ",option_length:" + option_length);
console.log("data_id:" + data_id + ",firstIp:" + firstIp + ",lastIp:" + lastIp);
};</script>
<input list="netsegments" id="input" onchange="inputSelect()" placeholder="xxx.xxx.xxx.xxx" />
<datalist id="netsegments">
<option label="10.0.23.xxx" value="10.0.23.1~62" data-value="10.0.23.1~62" data-id="1" firstIp="1" lastIp="62" />
<option label="10.0.23.xxx" value="10.0.23.64~127" data-value="10.0.23.64~127" data-id="2" firstIp="63" lastIp="127" />
<option label="10.0.23.xxx" value="10.0.23.129~192" data-value="10.0.23.129~192" data-id="3" firstIp="129" lastIp="192" />
</datalist>
</body>
</html>
<!-- 選擇option的value, 顯示在input里, 然后獲取對應(yīng)的屬性data-id, firstIp, lastIp -->
測試結(jié)果如下:
當(dāng)選擇第二個選項時候, console打印出結(jié)果:
input_select:10.0.23.64~127,option_length:3
data_id:2,firstIp:63,lastIp:127
從文中我們可以了解到有關(guān)于:“如何在html5實現(xiàn)datalist選中option選項的觸發(fā)事件?”這個問題的全部內(nèi)容,當(dāng)然如果你對于其他的內(nèi)容或者知識有興趣的話我們都能在W3Cschool這個網(wǎng)站中學(xué)習(xí)到更多的學(xué)習(xí)知識,小編也是在這個平臺總一路走出來的!希望小編的分享對大家有所收獲!