1、HTML元素捕获 (内容、属性)
text();
html();
var();
2、HTML元素设置(对内容进行操作)
attr();
3、HTML 元素添加
append();
prepend();
after();
before();
定义函数 给body添加元素
4 元素删除
remove(); 全部删除
empty();删除其中子元素
全部代码如下,
PS:因为是测试代码,所以有注释
HTML代码部分
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>HTML之捕获、设置、元素添加、元素删除</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="HTMLyuansu.js"></script>
</head>
<body>
<p id="pid">this is a p yuansu<a>这是一个a标签</a></p>
<button id="bid">click</button>
<p><input id="it" type="text" value="请输入您的名字"></p>
<p><a id="aid" href="http://www.hao123.com">成都大学</a></p>
<p id="pid2">最初内容</p>
<button id="bid2">click2</button>
<p id="pid3">最初内容</p>
<button id="bid3">click3</button>
<input type="text" id="it2" value="请输入您的年龄">
<button id="bid4">click4</button>
<a id="aid2" href="http://www.baidu.com">开始是百度,点击后是网址之家</a>
<button id="bid5">click5</button>
<br/>
<p id="pid4">Hellow world</p>
<button id="bid6">click6</button>
<p id="pid5">HTML元素添加</p>
<button id="bid7">click7</button>
<button onclick="appendText()">click8</button>
<div id="div1" style="width:100px;height:100px;border:1px solid black ;background-color:red">
<p>子元素1</p>
<p>子元素2</p>
<p>子元素3</p>
</div>
<button id="bit8">click9</button>
</body>
</html>
Javascript 代码部分(JQuery)
/**
* Created by qing on 2015/8/20.
*/
//两种方法区别:html() 可以获取内部子标签<p><a></a></P> 不仅可以显示a标签里的内容同时把<a>也显示出来
//而text()只能获取具体内容
$(document).ready(function () {
//HTML元素捕获 内容
//$("#bid").click(function(){
// alert("P元素内容为:"+$("#pid").text()); //.text() 获取元素内容方法一
//})
$("#bid").click(function(){
alert("P元素内容为:"+$("#pid").html()); //.html() 获取元素内容方法二
});
$("#bid").click(function(){
alert("P元素内容为:"+$("#it").val()); //.html() 获取元素内容方法不同
});
//获取元素属性
$("#bid").click(function(){
alert("P元素内容为:"+$("#aid").attr("href")); // attr("属性名")
});
//HTML元素设置
$("#bid2").click(function(){
$("#pid2").text("更改后的内容"); // text更改元素内容
});
$("#bid3").click(function(){
$("#pid3").html("<a href='http://www.hao123.com'>网址之家</a>"); // html可以更改元素标签
});
$("#bid4").click(function(){
$("#it2").val("18岁啦"); // val更改元素内容
});
$("#bid5").click(function(){
$("#aid2").attr({
"href":"http://www.hao123.com",
"title":"hellow" //增加属性
})
});
//回调函数 每点击一次就会设置一次 而不是像之前的执行一次 其他方法html val attr 也可用
$("#bid6").click(function(){
$("#pid4").text(function(i,ot){
return "old:"+ot+"\t"+"new:"+(i); //ot 表示原有的内容 i表示新值 默认为0, 可是怎么改变新值呢?
});
});
//HTML 添加元素
$("#bid7").click(function(){
//添加内容
//$("#pid5").append("这是添加的内容部分,") //在后面插入
//$("#pid5").prepend("这是添加的内容部分,") //在前面插入
//$("#pid5").after("这是添加的内容部分,") //在后面添加 换行
$("#pid5").before("这是添加的内容部分,") //在前面添加 换行
});
$("#bit8").click(function(){
//$("#div1").remove(); //全部删除
$("#div1").empty(); //删除里面的子元素
});
});
//追加新的元素
function appendText(){
var text1="<p>HTML添加方法</p>"
var text2=$("<p></p>").text("JQ添加方法");
var text3=document.createElement("p");
text3.innerHTML="JS添加方法";
$("body").append(text1,text2,text3);
alert("测试");
}