js動態生成html元素並為元素追加屬性


動態生成html元素的方法有三種:

 

第一種:document.createElement()創建元素,再用appendChild( )方法將元素添加到指定節點

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
<div id="main">
    <span id="login"></span>
</div>
</body>

<script>
    var link = document.createElement('a');
    link.setAttribute('href','#');
    link.setAttribute('id','login');
    link.style.color = 'green';
    link.innerhtml = '登錄';
    var main = document.getElementById('main');
    main.appendChild(link);
</script>

</html>

  

 

第二種:使用innerhtml直接將元素添加到指定節點

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
<div id="main">
    <span id="login"></span>
</div>
</body>

<script>
    var link = document.createElement('a');

    //使用innerhtml將元素直接添加到指定節點
    main.innerhtml = "<a href='#' id='login' style='color: red;'>登錄</a>";
</script>

</html>

  

虎課網https://www.wode007.com/sites/73267.html 設計塢https://www.wode007.com/sites/73738.html

第三種:jQuery創建節點

jQuery中創建DOM對象,使用jQuery的工廠函數$( )完成,格式如下:

$(html),$(html)會根據傳入的HTML標記字符串,創建一個DOM對象,並將這個DOM對象包裝成一個jQuery對象后再返回到前台頁面上。

jQuery中將創建的節點插入文本中,使用append( )等方法,jQuery中插入節點方法有:

1. append():向每個匹配的元素內部追加內容

2.appendTo():將所有匹配的元素追加到指定元素中,顛倒了常規的$(A).append(B)方法,不是將B追加到A中,而是將A追加到B中

3.prepend():向每個匹配的元素內部前置內容

4.prependTo():將所有匹配的內容前置到指定的元素中,與prpend( )方法顛倒

5.after():向每個匹配的元素之后插入內容

6.insertAfter():將所有匹配的元素插入到指定元素的后面,與after()方法顛倒

7.before():在每個匹配的元素之前插入內容

8.insertBefore():將每個匹配的元素插入到指定內容之前,與before()方法顛倒

<!DOCTYPE html> 
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title></title>
   <script src="jquery-1.11.1.min.js"></script>
   <style type="text/css">
       .newStyle{
            color:red
       }
   </style>

<script>
   $(function(){
   var link=$('<a href="#" id="link" style="color:pink">登錄</a>');
   $('#main').append(link).addClass("newStyle");
   })
</script>
</head>
 
<body>
   <div id="main"></div>
</body>
</html>

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM