1、获取内容:
三个简单实用的用于 DOM 操作的 jQuery 方法:
text() - 设置或返回所选元素的文本内容
<pre name="code" class="html">$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
html() - 设置或返回所选元素的内容(包括 HTML 标记)
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
val() - 设置或返回表单字段的值
$("#btn1").click(function(){
alert("Value: " + $("#test").val());
});
2、获取属性:
$("button").click(function(){
alert($("#w3s").attr("href"));
});
3、设置内容:
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
4、设置属性:
$("button").click(function(){
$("#w3s").attr("href","http://www.w3cschool.cc/jquery");
});
5、添加元素:
append() - 在被选元素的结尾插入内容
$("p").append("Some appended text.");
prepend() - 在被选元素的开头插入内容
$("p").prepend("Some prepended text.");
after() - 在被选元素之后插入内容
$("img").after("Some text after");
before() - 在被选元素之前插入内容
$("img").before("Some text before");
6、删除元素:
remove() - 删除被选元素(及其子元素)
$("#div1").remove();
empty() - 从被选元素中删除子元素
$("#div1").empty();
过滤删除:
$("p").remove(".italic");
7、获取并设置 CSS 类:
样式表:
.important
{
font-weight:bold;
font-size:xx-large;
}
.blue
{
color:blue;
}
addClass() - 向被选元素添加一个或多个类
$("button").click(function(){
$("h1,h2,p").addClass("blue");
$("div").addClass("important");
});
removeClass() - 从被选元素删除一个或多个类
$("button").click(function(){
$("h1,h2,p").removeClass("blue");
});
toggleClass() - 对被选元素进行添加/删除类的切换操作
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
css() - 设置或返回样式属性
$("p").css({"background-color":"yellow","font-size":"200%"});
8、尺寸: