jQuery removeAttr() 不删除 IE 中的“禁用”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10242205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:01:08  来源:igfitidea点击:

removeAttr() not removing "disabled" attribute in IE

jqueryinternet-explorer

提问by Maris Zemgalis

var disableSelection = function(){
    $("#elementId").attr("disabled","disabled");    
};

var enableSelection = function(){
    $("#elementId").removeAttr("disabled");
};

I have following requirements:

我有以下要求:

  1. disable SELECT element in order to restrict users from selecting options
  2. disabled SELECT element has some OPTION element already selected
  3. on submit event enable disabled SELECT element in order to save selected value
  1. 禁用 SELECT 元素以限制用户选择选项
  2. 禁用 SELECT 元素已经选择了一些 OPTION 元素
  3. 在提交事件上启用禁用的 SELECT 元素以保存选定的值

Adding attribute "disabled" works well for IE. Yet, when I try to remove attribute by using jQuery revomeAttr() method then instead of removing attribute:

添加属性“禁用”适用于 IE。然而,当我尝试使用 jQuery revomeAttr() 方法删除属性时,而不是删除属性:

  1. method adds "disabled" attribute to previously enabled SELECT element
  2. method doesn't remove "disabled" attribute
  1. 方法将“禁用”属性添加到先前启用的 SELECT 元素
  2. 方法不会删除“禁用”属性

回答by Jon

Use .propinstead of .attrto affect an element's disabled state:

使用.prop而不是.attr影响元素的禁用状态:

var disableSelection = function(){
    $("#elementId").prop("disabled", true);    
};

var enableSelection = function(){
    $("#elementId").prop("disabled", false);
};

For more information, see .prop() vs .attr().

有关更多信息,请参阅.prop() 与 .attr()

回答by Leniel Maccaferri

You can use removeProp('disabled')instead. It worked for me while removeAttr('disabled')didn't.

你可以removeProp('disabled')改用。它对我有用而removeAttr('disabled')没有。

回答by RodrigoB

Jquery Docs says, about .removeProp():

Jquery Docs 说,关于 .removeProp():

Note: Do not use this method to remove native properties such as checked, >disabled, or selected. This will remove the property completely and, once >removed, cannot be added again to element. Use .prop() to set these properties >to false instead.

Additional Notes:

In Internet Explorer prior to version 9, using .prop() to set a DOM element >property to anything other than a simple primitive value (number, string, or >boolean) can cause memory leaks if the property is not removed (using >.removeProp()) before the DOM element is removed from the document. To safely >set values on DOM objects without memory leaks, use .data().

注意:请勿使用此方法删除本机属性,例如已选中、> 已禁用或已选中。这将完全删除该属性,一旦 >removed,就无法再次添加到元素中。使用 .prop() 将这些属性设置为 false。

补充说明:

在版本 9 之前的 Internet Explorer 中,如果未删除属性(使用 > .removeProp()) 在从文档中删除 DOM 元素之前。要安全地在 DOM 对象上设置值而不会出现内存泄漏,请使用 .data()。