更改<option>中选定属性后,<select>窗口未更新

Mon*_*Ove 7 html firefox jquery

我正在创建的注册表单在选择下拉菜单中有商业和住宅选项.

根据活动页面类型,我更改默认选择的选项.

这是html:

<select class="type_c" name="type_c">  // default selected is business
    <option value="Business" selected="selected">Business</option>
    <option value="Residential">Residential</option>
</select>
Run Code Online (Sandbox Code Playgroud)

这是我在每个页面的页脚中运行的代码,用于更改这些值:

$(function(){

    var pageType = getPageType(); // returns either 'Business' or 'Residential'

    $('.type_c option').each(function(){
        $(this).removeAttr('selected');
    });

    $('.type_c option').each(function(){
        if($(this).html() == pageType)
            $(this).attr('selected','selected')
    });

});
Run Code Online (Sandbox Code Playgroud)

问题是当它在"住宅"页面上时,在DOM中选择"住宅"选项但在视觉上,选择了"商务"选项!

谢谢.

Tom*_*nti 4

由于这是在初始值之后更改属性,从技术上讲它是一个属性,您应该使用$(this).prop()而不是$(this).attr().

另外,尝试将值设置为true而不是selected

$(this).prop('selected',true);

或者,您也可以设置元素的值select

$('.type_c').val(pageType);