如何使用 jQuery 設定屬性的新值?


jQuery attr() 方法用於獲取屬性的值。還可以使用它來設定新值。我們將把屬性 href 的新值從教程時點 .com/css 設定為 tutorialspoint.com/html5。

你可以嘗試執行以下程式碼來了解如何在 jQuery 中設定屬性的新值 −

示例

線上演示

<html>
   <head>
      <title>Selector Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
            $("button").click(function(){
               $("#tpoint").attr("href", "https://tutorialspoint.tw/html5");
            });
         });
      </script>
   </head>
   <body>
      <p><a href="https://tutorialspoint.tw/css" id="tpoint">Tutorialspoint</a></p>
      <button>Set new value</button>
      <p>The value of above link will change on clicking the above button. This will set a new value for the attribute. Check before and after button click.</p>
   </body>
</html>

更新於:2020 年 2 月 13 日

627 次瀏覽

啟動你的事業

完成課程獲得認證

立即開始
廣告