Jquery select change

[亡魂溺海] 提交于 2019-12-05 15:26:46

问题


<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

$(document).ready(function() {  
    $('#Nazione').change(function(){

        alert( $(this).find("option:selected").attr('prefix') );
        alert( $(this).attr('prefix') );
    });
  });

I have alert NULL... WHy?


回答1:


Your code is fine. Here's a demo : http://jsfiddle.net/hKktc/1/

The reason you're not getting a value for the second alert call is because the attribute prefix doesn't exist for the select and only exists for the option




回答2:


In your code, $(this) refers to the <select>, not the option. The prefix attribute does not exist on the <select>

This will cause the problem with the second example.




回答3:


The 2nd alert will return null, because <select> has no attribute prefix.




回答4:


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




回答5:


You probably wanted .val() not .attr('prefix'), to obtain selected value of <select>.

$(document).ready(function() {  
    $('#Nazione').change(function(){

        alert( $(this).find("option:selected").attr('prefix') );
        alert( $(this).val('prefix') );
    });
  });


来源:https://stackoverflow.com/questions/5961957/jquery-select-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!