简体   繁体   English

如何使用jQuery在选择框选项中获取类的值

[英]how do I get the value of a class in the select box option with jquery

my code : 我的代码:

<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>

here's my jquery code : 这是我的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);
});

result in console : 结果在控制台中:

name and id = undefined

so, how to display the variable name and variable id? 那么,如何显示变量名称和变量ID? Thx.. 谢谢..

So, putting <span> inside of an option actually violates the HTML spec ( It is bad to put <span /> tags inside <option /> tags, only for string manipulation not styling? ), so depending on the user's browser, the spans may not even be present in the dom (replaced instead with a text-type node containing the contents of the spans). 因此,将<span>放在选项内实际上违反了HTML规范( 将<span />标记放在<option />标记内很不好,仅用于字符串操作而不是样式设置? ),因此取决于用户的浏览器,在dom中甚至不存在跨度(用包含跨度内容的文本类型节点代替)。

You'll probably want to use something like this instead 您可能想要使用类似这样的东西

$(".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/ 小提琴: http//jsfiddle.net/9nn1rune/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM