如何在 jQuery 中将属性添加到特定的 HTML 标签中?

jqueryweb developmentfront end technology更新于 2026/1/27 23:07:17

使用 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>

相关文章