Always use the prop()
method to enable or disable elements when using jQuery (see below for why).
(在使用jQuery时, 始终使用prop()
方法启用或禁用元素(请参阅下面的原因)。)
In your case, it would be:
(在你的情况下,它将是:)
$("#edit").click(function(event){
event.preventDefault();
$('.inputDisabled').prop("disabled", false); // Element(s) are now enabled.
});
jsFiddle example here.
(这里有jsFiddle示例。)
Why use prop()
when you could use attr()
/ removeAttr()
to do this?
(为什么在使用attr()
/ removeAttr()
执行此操作时使用prop()
?)
Basically, prop()
should be used when getting or setting properties (such as autoplay
, checked
, disabled
and required
amongst others).
(基本上,在获取或设置属性时应使用prop()
(例如autoplay
, checked
, disabled
和其他required
)。)
By using removeAttr()
, you are completely removing the disabled
attribute itself - while prop()
is merely setting the property's underlying boolean value to false.
(通过使用removeAttr()
,您将完全删除disabled
属性本身 - 而prop()
仅将属性的基础布尔值设置为false。)
While what you want to do can be done using attr()
/ removeAttr()
, it doesn't mean it should be done (and can cause strange/problematic behaviour, as in this case).
(虽然您想要做的事情可以使用attr()
/ removeAttr()
,但这并不意味着它应该完成(并且可能导致奇怪/有问题的行为,如本例所示)。)
The following extracts (taken from the jQuery documentation for prop() ) explain these points in greater detail:
(以下摘录(摘自prop()的jQuery文档 )更详细地解释了这些要点:)
"The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr()
method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop()
method provides a way to explicitly retrieve property values, while .attr()
retrieves attributes."
(“在特定情况下,属性和属性之间的区别很重要。在jQuery 1.6之前, .attr()
方法在检索某些属性时有时会考虑属性值,这可能会导致行为不一致。从jQuery 1.6开始, .prop()
方法提供了一种显式检索属性值的方法,而.attr()
检索属性。“)
"Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value
property of input elements, the disabled
property of inputs and buttons, or the checked
property of a checkbox. The .prop()
method should be used to set disabled
and checked
instead of the .attr()
method. The .val()
method should be used for getting and setting value
."
(“属性通常会影响DOM元素的动态状态,而不会更改序列化的HTML属性。例如输入元素的value
属性,输入和按钮的disabled
属性,或复选框的checked
属性.prop()
方法应该用于设置disabled
和checked
而不是.attr()
方法。应该使用.val()
方法来获取和设置value
。“)