gpt4 book ai didi

javascript - JQuery 1.6 中的 removeProp 和 removeAttr 有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 13:25:20 25 4
gpt4 key购买 nike

如果你 removeProp 在你应该使用 removeAttr() 的东西上,它会默默地失败吗?它会工作吗?它实际上会删除整个属性还是仅删除其中的值?

如果使用 removeProp() 添加了 checked,是否可以使用 removeAttr() 将其删除?

很多问题!

最佳答案

official jQuery blog提供了一个非常清晰的解释:

In the 1.6 release we’ve split apart the handling of DOM attributes and DOM properties into separate methods. The new .prop() method sets or gets properties on DOM elements, and .removeProp() removes properties. In the past, jQuery has not drawn a clear line between properties and attributes. Generally, DOM attributes represent the state of DOM information as retrieved from the document, such as the value attribute in the markup . DOM properties represent the dynamic state of the document; for example if the user clicks in the input element above and types def the .prop("value") is abcdef but the .attr("value") remains abc.

In most cases, the browser treats the attribute value as the starting value for the property, but Boolean attributes such as checked or disabled have unusual semantics.

For example, consider the markup <input type="checkbox" checked>. The presence of the checked attribute means that the DOM .checked property is true, even though the attribute does not have a value. In the code above, the checked attribute value is an empty string (or undefined if no attribute was specified) but the checked property value is true.

Before jQuery 1.6, .attr("checked") returned the Boolean property value (true) but as of jQuery 1.6 it returns the actual value of the attribute (an empty string), which doesn’t change when the user clicks the checkbox to change its state.

There are several alternatives for checking the currently-checked state of a checkbox. The best and most performant is to use the DOM property directly, as in this.checked inside an event handler when this references the element that was clicked. In code that uses jQuery 1.6 or newer, the new method $(this).prop("checked") retrieves the same value as this.checked and is relatively fast. Finally, the expression $(this).is(":checked") works for all versions of jQuery.

关于javascript - JQuery 1.6 中的 removeProp 和 removeAttr 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5894229/

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