获得内容 - text()、html() 以及 val()
text() - 设置或返回所选元素的文本内容
html() - 设置或返回所选元素的内容(包括 HTML 标记)
val() - 设置或返回表单字段的值
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
$("#btn1").click(function(){
alert("Value: " + $("#test").val());
});
获取属性 - attr()
$("button").click(function(){
alert($("#w3s").attr("href"));
});
设置内容 - text()、html() 以及 val()
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
设置属性 - attr()
$("button").click(function(){
$("#w3s").attr("href","http://www.w3school.com.cn/jquery");
});
添加新的 HTML 内容
append() - 在被选元素的结尾插入内容
prepend() - 在被选元素的开头插入内容
after() - 在被选元素之后插入内容
before() - 在被选元素之前插入内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../jquery/jquery.js"></script>
<script>
$(function(){
$("#b1").click(function(){
$("#p1").after("<div style='background-color: black;width: 30px;height: 30px;'></div>")
$("#p2").append("<div style='background-color: red;width: 30px;height: 30px;'></div>")
})
});
</script>
</head>
<body>
<p id="p1" style="border: 1px black solid;">after</p>
<p id="p2" style="border: 1px black solid;">append</p>
<button id="b1">点击</button>
</body>
</html>