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明显更加方便快捷。

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值