考虑到以下情况:

<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的值时,选择被改变。我假设我需要做一些关于获得当前选择的值…?


当前回答

这是因为元素是“Select”而不是“Option”,其中有自定义标记。

试试这个:$("#location option:selected").attr("myTag")。

希望这能有所帮助。

其他回答

你很接近了:

var myTag = $(':selected', element).attr("myTag");

最简单的,

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

直接的方法是:

获取所选选项属性值:

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

获取选定文本:

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

获取所选值:

var selectedOptionValue = $('#location').val();

试试这个:

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

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

在change()的回调函数中,this指的是select,而不是所选的选项。

如果你想根据动态行ID调用:

var data = $(`#var_name_${row_id} option:selected`).attr('value2');