jQuery 选择更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5961957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery select change
提问by Ste
<select id="Nazione" name="Nazione">
<option prefix='+93' value='AF' >Afghanistan </option>
<option prefix='+355' value='AL' >Albania </option>
<option prefix='+213' value='DZ' >Algeria </option>
<option prefix='+376' value='AD' >Andorra .... etc
</select>
and this js
而这个js
$(document).ready(function() {
$('#Nazione').change(function(){
alert( $(this).find("option:selected").attr('prefix') );
alert( $(this).attr('prefix') );
});
});
I have alert NULL... WHy?
我有警报 NULL... 为什么?
采纳答案by JohnP
Your code is fine. Here's a demo : http://jsfiddle.net/hKktc/1/
你的代码没问题。这是一个演示:http: //jsfiddle.net/hKktc/1/
The reason you're not getting a value for the second alert call is because the attribute prefixdoesn't exist for the selectand only exists for the option
您没有获得第二个警报调用的值的原因是该属性prefix不存在于select并且仅存在于option
回答by DanielB
The 2nd alertwill return null, because <select>has no attribute prefix.
第二个alert将返回 null,因为<select>没有属性prefix。
回答by James Wiseman
In your code, $(this)refers to the <select>, not the option. The prefixattribute does not exist on the <select>
在您的代码中,$(this)指的是<select>,而不是选项。该prefix属性不存在于<select>
This will cause the problem with the second example.
这将导致第二个示例出现问题。
回答by phil
What is it you are expecting exactly?
你究竟在期待什么?
I find that the second alert - alert( $(this).attr('prefix') );is the one causing a problem.
As is, you get an alert of the prefix number, then an alert of null (caused by the second alert).
我发现第二个警报 -alert( $(this).attr('prefix') );是导致问题的警报。照原样,您会收到前缀号码的警报,然后是空警报(由第二个警报引起)。
回答by vitas
You probably wanted .val()not .attr('prefix'), to obtain selected value of <select>.
你可能想.val()不是.attr('prefix'),获得的设定值<select>。
$(document).ready(function() {
$('#Nazione').change(function(){
alert( $(this).find("option:selected").attr('prefix') );
alert( $(this).val('prefix') );
});
});

