1. 程式人生 > >jQuery HTML簡單操作

jQuery HTML簡單操作

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})

 

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->list5index()中的數字從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:刪除掉其中的子元素