考虑到以下情况:

<select id="location">
    <option value="a" myTag="123">My option</option>
    <option value="b" myTag="456">My other option</option>
</select>

<input type="hidden" id="setMyTag" />

<script>
    $(function() {
        $("#location").change(function(){
            var element = $(this);
            var myTag = element.attr("myTag");

            $('#setMyTag').val(myTag);
        });
    });
</script>

这行不通…… 我需要做什么来让隐藏字段的值更新到myTag的值时,选择被改变。我假设我需要做一些关于获得当前选择的值…?


当前回答

假设你有很多选择。这可以做到:

$('.selectClass').change(function(){
    var optionSelected = $(this).find('option:selected').attr('optionAtribute');
    alert(optionSelected);//this will show the value of the atribute of that option.
});

其他回答

最简单的,

$('#location').find('option:selected').attr('myTag');

直接的方法是:

获取所选选项属性值:

var selectedOptionAttributeValue =   $('#location option:selected').attr('myTag');

获取选定文本:

 var selectedOptionText = $('#location').text();

获取所选值:

var selectedOptionValue = $('#location').val();
$("body").on('change', '#location', function(e) {

 var option = $('option:selected', this).attr('myTag');

});

试试这个:

$(function() { 
    $("#location").change(function(){ 
        var element = $(this).find('option:selected'); 
        var myTag = element.attr("myTag"); 

        $('#setMyTag').val(myTag); 
    }); 
}); 

试试这个例子:

$("#location").change(function(){

    var tag = $("option[value="+$(this).val()+"]", this).attr('mytag');

    $('#setMyTag').val(tag); 

});