jQuery HTML-捕获
JQuery也封装了HTML DOM操作,在JS中通过HTML DOM修改、添加和删除元素。具体的可以参考API--jQuery DOM
以下是一些常用功能的示例
HTML文件:
1<body>
2 <p id="text">This is a text<a>This is a link</a></p>
3 <p><input type="text" id="inputId"></p>
4 <p><a id="aId" href="https://www.baidu.com/">Baidu</a></p>
5 <button id="btn">click me</button>
6</body>
JS文件
- 弹出:
text:This is a textThis is a link
1$("document").ready(function () {
2 $("#btn").click(function () {
3 alert("text:"+ $("#text").text());
4 })
5})
- 弹出:
text:This is a textThis is a link
1$("document").ready(function () {
2 $("#btn").click(function () {
3 alert("text:"+ $("#text").html());
4 })
5})
.html()
是可以获取到内部标签的,而.text()
只能获取具体的内容。
- 弹出输入框中的内容。
1$("document").ready(function () {
2 $("#btn").click(function () {
3 alert("text:"+ $("#inputId").val());
4 })
5})
- 弹出a标签的的href属性内容
1$("document").ready(function () {
2 $("#btn").click(function () {
3 alert("text:"+ $("#aId").attr("href"));
4 })
5})
jQuery HTML-设置
仍以上方的HTML文件内容为例
- 基础使用
1// This is a textThis is a link 内容变为 Hello
2$("#text").text("Hello");
3// This is a textThis is a link 内容变为 Baidu 并且可以跳转
4$("#text").html("<a href='https://www.baidu.com/'>Baidu</a>");
5// 输入框内容变为 What
6$("#inputId").val("What");
7// a标签的属性发生变化
8$("#aId").attr({
9 "href":"https://www.google.com/",
10 "title":"hello"
11})
- 回调方法
text()
、html()
以及val()
拥有回调函数。:
回调函数由两个参数:(被选元素列表中当前元素的下标,以及原始(旧的)值。) 然后以函数新值返回您希望使用的字符串。
1<button id="btn">测试下标</button>
2<div>
3 <p class="list">list1</p>
4 <p class="list">list2</p>
5 <p class="list">list3</p>
6 <p class="list">list4</p>
7 <p class="list">list5</p>
8</div>回调函数:
1$("document").ready(function () {
2 $("#btn").click(function () {
3 $(".list").text(function(i,oriText){
4 alert("原文本:"+oriText+" 新文本:hello world! index("+i+")");
5 });
6 })
7})弹出5次,其中
oriText
中的内容从list1->list5
,index()
中的数字从0->4
jQuery HTML-添加元素
- 添加内容
1$("#pId").append("append插入") // 在p元素的内容之后插入内容,即显示:one append插入
2$("#pId").prepend("prepend插入 ") // 在p元素的内容之前插入内容,即显示:prepend插入 one
3$("#pId").before("before插入"); // 在p元素的内容之前插入内容,即显示:before插入(换行)one
4$("#pId").after("after插入"); // 在p元素的内容之后插入内容,即显示:one(换行)after插入
- 添加元素
可以添加的元素方式包括HTML、jQuery、DOM
1//HTML
2var text1 = "<p>html</p>";
3//jQuery
4var text2 = $("<p></p>").text("jQuery");
5//DOM
6var text3 = document.createElement("p");
7text3.innerHTML = "DOM";
8//在body元素中追加元素及内容
9$("body").append(text1,text2,text3)
jQuery HTML-删除元素
remove
:整个删除掉这个元素empty
:删除掉其中的子元素