gpt4 book ai didi

javascript - 如何使用 jQuery 删除 "disabled"属性?

转载 作者:IT老高 更新时间:2023-10-28 13:11:21 31 4
gpt4 key购买 nike

我必须先禁用输入,然后单击链接以启用它们。

这是我迄今为止尝试过的,但它不起作用。

HTML:

<input type="text" disabled="disabled" class="inputDisabled" value="">

jQuery:

$("#edit").click(function(event){
event.preventDefault();
$('.inputDisabled').removeAttr("disabled")
});


这显示了 true 然后 false 但输入没有任何变化:

$("#edit").click(function(event){
alert('');
event.preventDefault();
alert($('.inputDisabled').attr('disabled'));
$('.inputDisabled').removeAttr("disabled");
alert($('.inputDisabled').attr('disabled'));
});

最佳答案

始终使用 prop() 在使用 jQuery 时启用或禁用元素的方法(原因见下文)。

在你的情况下,它会是:

$("#edit").click(function(event){
event.preventDefault();
$('.inputDisabled').prop("disabled", false); // Element(s) are now enabled.
});

jsFiddle example here.


Why use prop() when you could use attr()/removeAttr() to do this?

基本上在获取或设置properties时应该使用prop()(如autoplaycheckeddisabledrequired 等)。

通过使用 removeAttr(),您将完全删除 disabled 属性本身 - 而 prop() 只是设置属性的底层 bool 值值为假。

虽然您想做的事情可以使用 attr()/removeAttr() 来完成,但这并不意味着它应该完成(并且可能导致奇怪/有问题的行为,如本例所示)。

以下摘录(摘自 jQuery documentation for prop())更详细地解释了这些要点:

"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."

"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."

关于javascript - 如何使用 jQuery 删除 "disabled"属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13626517/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com