JavaScript及jquery创建节点及节点属性

通过JavaScript原生接口创建元素节点及节点属性,做以下示例演示:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<title>无标题文档</title>
<style>
.first{
  background-color:green;
  width:150px;
  height:150px;
  border:solid black;
  font-size:30px;
  font-family:微软雅黑;
}
.second{
  background-color:blue;
  width:150px;
  height:150px;
  border:solid black;
  font-size:30px;
  font-family:微软雅黑;
}
</style>
</head>

<body>
<h1>动态创建元素节点</h1>
<div class="first">
   <p>Hi,this is the first node</p>
</div>

<script type="text/javascript">
var body=document.querySelector('body');

document.addEventListener('click',function(){
	//创建新的节点元素;
	   var newdiv1=document.createElement('div');
	   var newdiv2=document.createElement('div');
	   //设置新的元素节点属性;
	   newdiv1.setAttribute('class','second');
	   //添加文本;
	   newdiv2.innerHTML="Hi,this is the second node";
	   //加入到文档中;
	   newdiv1.appendChild(newdiv2);
	   body.appendChild(newdiv1);
	},false)

</script>
</body>
</html>

浏览器中预览效果:

单击页面,显示效果如下:

流程中涉及的一点方法:

  • 创建元素:document.createElement
  • 设置属性:setAttribute
  • 添加文本:innerHTML
  • 加入文档:appendChild

通过jquery创建元素节点及元素属性示例如下:

<script type="text/javascript">
     var $body=$('body');
	 $body.on('click',function(){
       var newdiv=$("<div class='second'><div>Hi,this is the second node</div></div>");
	   $body.append(newdiv);
	 })
</script>

运行结果同JavaScript。但jquery明显更加方便快捷。

猜你喜欢

转载自blog.csdn.net/qq_34538534/article/details/82918777