gpt4 book ai didi

javascript - 如何使用 jquery 获取选择框选项中类的值

转载 作者:行者123 更新时间:2023-12-03 11:16:09 25 4
gpt4 key购买 nike

我的代码:

<select class='country'>
<option value='usa'><span class='nameCountry'>America</span> <span class='idCountry'>1</span></option>
<option value='sgd'><span class='nameCountry'>Singapura</span> <span class='idCountry'>2</span></option>
<option value='thi'><span class='nameCountry'>Thailand</span> <span class='idCountry'>3</span></option>
</select>

<div class="result">
<input type="text" name="kodeCountry" />
<input type="text" name="idCountry" />
<input type="text" name="nameCountry" />
</div>

这是我的 jquery 代码:

$(".country").change(function(){
var kode = $(this).val();
var name = $(".country option .nameCountry").html();
var id = $(".country option .idCountry").html();
console.log(kode);
console.log(name);
console.log(id);
});

控制台结果:

name and id = undefined

那么,如何显示变量名和变量id呢?谢谢..

最佳答案

所以,输入<span>选项内部实际上违反了 HTML 规范 ( It is bad to put <span /> tags inside <option /> tags, only for string manipulation not styling? ),因此根据用户的浏览器,跨度甚至可能不会出现在 dom 中(而是替换为包含跨度内容的文本类型节点)。

您可能会想使用类似的东西

$(".country").on('change', function(e){
var kode = $(this).val();
var $selected = $('option:selected', this);
var parts = $selected.text().split(/\W+/);
var name = parts[0]
var id = parts[1]
console.log(kode);
console.log(name);
console.log(id);
});

fiddle :http://jsfiddle.net/9nn1rune/

关于javascript - 如何使用 jquery 获取选择框选项中类的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27338914/

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