首頁  >  文章  >  web前端  >  使用 jQuery 停用和啟用元素的最佳方法是什麼:布林屬性的 prop() 與 attr()?

使用 jQuery 停用和啟用元素的最佳方法是什麼:布林屬性的 prop() 與 attr()?

Susan Sarandon
Susan Sarandon原創
2024-10-19 19:12:30714瀏覽

What's the Optimal Method for Disabling and Enabling Elements with jQuery: prop() vs. attr() for Boolean Attributes?

如何使用jQuery 有效停用與啟用元素:了解attr() 和prop() 之間的差異

問題:

您嘗試最初停用輸入,然後在點擊連結時啟用它們,但您目前的jQuery 解決方案無法正常運作。

HTML:

<code class="html"><input type="text" disabled="disabled" class="inputDisabled" value=""></code>

jQuery:

<code class="javascript">$("#edit").click(function(event){
   event.preventDefault();
   $('.inputDisabled').removeAttr("disabled")
});</code>

>

您正在使用removeAttr()來刪除「disabled」屬性,但這種方法有局限性,尤其是像「disabled」這樣的布林屬性。

解決方案:使用 prop() 而不是 attr()

對於布林屬性,建議使用 prop() 方法而不是 attr()。此方法明確修改元素的底層屬性值,這對於布林屬性來說更加高效且合適。

更新了 jQuery:

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

為什麼prop() 優於 attr() 對於布林屬性?

  • 一致性: prop() 一致地設定屬性值,而attr() 可能會導致意外行為
  • 準確性: prop() 檢索並設定實際的屬性值,而attr() 可能會根據屬性傳回或設定不同的值。
  • 效率: prop() 對於布林屬性來說更高效,因為它直接修改屬性而不涉及屬性。

注意: 在 jQuery 之前的版本中到 3.0,布林屬性上的removeAttr() 也會將對應的屬性設為 false。此行為在後續版本中已被棄用,凸顯了使用 prop() 取得布林屬性的重要性。

以上是使用 jQuery 停用和啟用元素的最佳方法是什麼:布林屬性的 prop() 與 attr()?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn