如何使用 jQuery 向特定 HTML 標籤新增屬性?
使用 attr() 方法可在 jQuery 中向特定 HTML 標籤新增屬性。
示例
嘗試執行以下程式碼瞭解如何向特定 HTML 標籤新增屬性
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(document).ready(function(){ $("button.button1").attr("myid", "myvalue"); $('button').on('click', function() { if (this.hasAttribute("myid")) { alert('True: The new attribute added successfully.') } else { alert('False') } }) }); }); </script> </head> <body> <button class='button1'> Button 1 </button> </body> </html>
廣告