JQuery - DOM节点与jQuery节点的创建

DOM创建节点及节点属性

流程中涉及的一点方法:

  • 创建元素:document.createElement
  • 设置属性:setAttribute
  • 添加文本:innerHTML
  • 加入文档:appendChild
<!DOCTYPE html>
<html>
<head>
	<title></title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <script src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script>
    <style>
        .box1,.box2 {width: 120px;height: 120px;background-color: #f5f5f5;}
        .box1 div,.box2 div {width: 100px;height: 100px;margin: 0 auto 10px auto;}
        .box1 div {background: pink;}
        .box2 div {background: yellow;}
    </style>
</head>
<body>
    <h2>动态创建元素节点</h2>
    <div class="box1">
        <div class="vegeta">点击body区域会动态创建元素节点</div>
    </div>
    <script type="text/javascript">
        var body = document.querySelector('body');
        document.addEventListener('click',function(){
	    	//创建2个div元素
		    var box2div = document.createElement('div')
		    var box2vegeta = document.createElement("div");
		    //给2个div设置不同的属性
		    box2div.setAttribute('class', 'box2')
		    box2vegeta.className = 'vegeta'
		    box2vegeta.innerHTML = "动态创建DIV元素节点";
		    //2个div合并成包含关系
		    box2div.appendChild(box2vegeta)
		   	//绘制到页面body
		   	body.appendChild(box2div)
	    },false)
    </script>
</body>
</html>

jQuery节点创建与属性的处理

这就是jQuery创建节点的方式,让我们保留HTML的结构书写方式,非常的简单、方便和灵活。

<!DOCTYPE html>
<html>
<head>
	<title></title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <script src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script>
    <style>
        .box1,.box2 {width: 120px;height: 120px;background-color: #f5f5f5;}
        .box1 div,.box2 div {width: 100px;height: 100px;margin: 0 auto 10px auto;}
        .box1 div {background: pink;}
        .box2 div {background: yellow;}
    </style>
</head>
<body>
    <h2>动态创建元素节点</h2>
    <div class="box1">
        <div class="vegeta">点击body区域会动态创建元素节点</div>
    </div>
    <script type="text/javascript">
        var $body = $('body');
        $body.on('click', function() {
            //通过jQuery生成div元素节点
            var div = $("<div class='box2'><div class='vegeta'>动态创建DIV元素节点</div></div>")
            $body.append(div)
        })
    </script>
</body>
</html>

这两个的效果一样:

猜你喜欢

转载自blog.csdn.net/cai181191/article/details/81076924