简体   繁体   English

使用jQuery无法在IE中添加/删除选择选项

[英]Adding/removing select options with jQuery not working in IE

When the first dropdown is selected, I'm trying to dynamically update the options in the second dropdown. 选择第一个下拉列表时,我正在尝试动态更新第二个下拉列表中的选项。 It's working fine in FF, Chrome etc but doesn't work in IE 8/9 and I don't understand why. 它在FF,Chrome等工作正常,但在IE 8/9中不起作用,我不明白为什么。 Here's a jsFiddle 这是一个jsFiddle

<div class="custom-field">            
    <label for="dropdown1">Select country:</label>
    <select id="dropdown1" name='properties[country]'>
        <option value="USA">USA</option>
        <option value="JAPAN">JAPAN</option>
    </select>
</div>
<div class="custom-field">            
    <label for="dropdown2">Select font:</label>
    <select id="dropdown2" name='properties[font]'>
        <option class="us" value="font1">Font1</option>
        <option class="us" value="font2">Font2</option>
        <option class="us" value="font3">Font3</option>
        <option class="jp" value="font4">Font4</option>
        <option class="jp" value="font5">Font5</option>
        <option class="jp" value="font6">Font6</option>              
    </select>
</div>  



function showFont(fontOpt){
    if (jQuery('#dropdown1').val() === 'USA'){
        var showOptions = fontOpt.filter('.us');
    } else {    
        var showOptions = fontOpt.filter('.jp');
    }
    jQuery('#dropdown2').html(showOptions);
    jQuery('#dropdown2').prop('selectedIndex', 0);
}


$(document).ready(function() {
    // get the child elements of font dropdown
    var fontOptions = $("#dropdown2").children('option');    
    $("#dropdown2").html('');

    showFont(fontOptions);

    $('#dropdown1').on("change", function(e){
        showFont(fontOptions);
    });    

});
$("#dropdown2").html('');

problem is with this line. 问题在于这条线。 Remove this line and your code will work fine. 删除此行,您的代码将正常工作。

Instead of this you may use 你可以使用而不是这个

$("#dropdown2").children('option').remove();

Is this your HTML code above? 这是您的HTML代码吗? If so, then you need to put script = 'text/javascript' from function showFont to the end. 如果是这样,那么你需要将函数showFont中的script ='text / javascript' 放到最后。 This makes the computer read the code as javascript and not HTML which i think your asking it to do. 这使得计算机将代码读作javascript,而不是我认为你要求它做的HTML。 Hope this helps. 希望这可以帮助。

Comment the following line in jquery; 在jquery中注释以下行;

//$("#dropdown2").html('');

it will work. 它会工作。

You can use short method like below: 你可以使用如下的简短方法:

 var fontOptions = $("#dropdown2").children('option');    
 $("#dropdown2").html('');

Instead of 代替

var fontOptions = $("#dropdown2").children('option').remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM