jQuery 动态生成 div 标签实现方法


发布日期 : 2020-04-16 22:51:27 UTC

访问量: 10 次浏览

jQuery 创建一个div元素

创建一个使用jQuery的 <div> 元素可以通过以下步骤完成。

步骤:

  • 创建一个新的 <div> 元素。
  • 选择一个父元素,把这个新创建的元素放在那里。
  • 将创建的div元素放入父元素。

例子1:
这个例子创建了一个 <div> 元素,并使用 append() 方法将该元素追加到父元素的末端。

<!DOCTYPE html>  
<html>  
  
<head> 
    <title> 
        Create div element using jQuery
    </title>
      
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
      
    <style>
        #parent {
            height: 100px;
            width: 300px;
            background: green;
            margin: 0 auto;
        }
        #newElement {
            height: 40px;
            width: 100px;
            margin: 0 auto;
            color: white
        }
    </style>
</head> 
          
<body style = "text-align:center;">  
      
    <h1 style = "color:green;" >  
        GeeksForGeeks  
    </h1>  
      
    <div id= "parent"></div>
          
    <br><br>
      
    <button onclick="insert()"> 
        insert
    </button> 
      
    <!-- Script to insert div element -->
    <script> 
        function insert() {
            $("#parent").append('<div id = "newElement">A '
                + 'Computer Science portal for geeks</div>');
        }
    </script> 
</body>  
  
</html>

输出:

  • 在点击按钮之前。

jQuery 创建一个div元素
* 点击该按钮后。

jQuery 创建一个div元素

例子2:
这个例子创建了一个 <div> 元素,并使用 prependTo() 方法将该元素追加到父元素的开头。

<!DOCTYPE html>  
<html>  
  
<head> 
    <title> 
        Create div element using jQuery
    </title>
      
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
      
    <style>
        #parent {
            height: 100px;
            width: 300px;
            background: green;
            margin: 0 auto;
        }
        #newElement {
            height: 40px;
            width: 100px;
            margin: 0 auto;
            color: white
        }
    </style>
</head> 
          
<body style = "text-align:center;">  
      
    <h1 style = "color:green;" >  
        GeeksForGeeks  
    </h1>  
      
    <div id= "parent"></div>
      
    <br><br>
      
    <button onclick="insert()"> 
        insert
    </button> 
              
    <script> 
        function insert() {
         $('<div id = "newElement">A Computer Science portal'
            + ' for geeks</div>').prependTo($('#parent'));         
        } 
    </script> 
</body>  
  
</html>

输出:

  • 在点击按钮之前。

jQuery 创建一个div元素
* 点击该按钮后。

jQuery 创建一个div元素