如何使用 jQuery 動態建立 div?


要動態建立一個 div,請使用 html() 方法。你可以嘗試執行下面的程式碼,瞭解如何透過單擊按鈕來動態建立 div −

範例

線上示範

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("body").html("<div>This is a new div.</div>");
      });
    });
</script>
</head>
<body>

  <button>Create a new div</button>

<p>This is demo text.</p>
</body>
</html>

更新時間:20-6-2020

1K+ 瀏覽量

開啟你的職業生涯

完成課程後獲得認證

立即開始
廣告