将下拉列表设置为只读

Make dropdown read-only

我正在尝试编写一个代码,使 HTML 下拉菜单只读,而不是 "disabled",因为我想捕获当前表单中来自以前表单的默认值。

我编写了以下代码,它在 Chrome 中运行良好,但在 IE 中无法运行。可能的解决方案是什么。

下面是我写的 jquery 代码。

$("#Q4Q25xP1_1, #Q4Q25xP1_2, #Q4Q25xP1_3, #Q4Q25xP1_4, #Q4Q25xP1_5").each(function(){
                $(this).on("mousedown", function(e){
                                return false;
                }).on("change", function(){
                                $(this).find('option').each(function(i, opt) {
                                    opt.selected = opt.defaultSelected;
                                });
                }).css("background-color","grey");
});

您可以尝试使用 CSS:

pointer-events 设置为 none
<select style="pointer-events:none;">
....
$("#Q4Q25xP1_1, #Q4Q25xP1_2, #Q4Q25xP1_3, #Q4Q25xP1_4, #Q4Q25xP1_5").each(function(){
      $(this).attr('disabled','disabled');
}

"Change" 事件在浏览器中不一致,在 Firefox 和 Chrome 中正常工作 但在 IE 中需要点击两次,首先删除 "indeterminate" 状态,然后再次触发更改事件。因此您需要使用触发点击事件来进行第二次点击,以便事件初始化和工作。

因此您需要第二次使用触发器 mousedown 在同一元素上应用 mousedown 事件而不是更改事件正常工作

试试这个,只禁用未选中的选项

$("#Q4Q25xP1_1,#Q4Q25xP1_2,#Q4Q25xP1_3").find("option").each(function () {
    if ($(this).attr("selected") != "selected") {
        $(this).attr("disabled", 'disabled');
    }
});

这是供参考的jsfiddle https://jsfiddle.net/3v0w9n3r/

它适用于包括 IE 在内的所有浏览器。