使用jQuery可以友善的添加新的HTML元素。
下面的方法用于添加HTML元素:
append() – 在指定的元素的尾部添加一個新内容。
prepend() -在指定的元素裡前部添加新内容。
after() – 在指定元素前添加新内容
before() -在指定元素的後面添加新内容。
乍一看append,prepend 和after,before似乎功能一樣,但append,prepend指在選中的元素本身(内部)的前面和後面,而after,before指在選擇中的元素的前面和後面。
jQuery使用下面兩個方法來删除或是清空某個HTML元素。
remove() – 删除指定的元素(包括其子元素)
empty() – 清空指定元素的子元素
例如:
JQuery Demo
$(document).ready(function () {
$("button").click(function () {
$("#div1").remove();
});
});
This is some text in the div.
This is a paragraph in the div.
This is another paragraph in the div.
Remove div element
JQuery Demo
$(document).ready(function () {
$("button").click(function () {
$("#div1").remove();
});
});
This is some text in the div.
This is a paragraph in the div.
This is another paragraph in the div.
Remove div element
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yNxQDZkRDOyMzM0MTYwcjMzE2YwkTNihTYjljY4EDOw8CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
empty() 示例:
[html]
JQuery Demo
$(document).ready(function () {
$("button").click(function () {
$("#div1").empty();
});
});
This is some text in the div.
This is a paragraph in the div.
This is another paragraph in the div.
Empty the div element
JQuery Demo
$(document).ready(function () {
$("button").click(function () {
$("#div1").empty();
});
});
This is some text in the div.
This is a paragraph in the div.
This is another paragraph in the div.
Empty the div element
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yNxQDZkRDOyMzM0MTYwcjMzE2YwkTNihTYjljY4EDOw8CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
jQuery的remove()方法也支援一個參數,可以用于過濾一些需要删除的HTML元素。這個參數可以為任何有效的jQuery selector.
比如下面代碼隻删除class=”italic”的
元素:
[javascript]
$("p").remove(".italic");
$("p").remove(".italic");