一、获得内容及属性
三个简单实用的用于 DOM 操作的 jQuery 方法:
- text() - 设置或返回所选元素的文本内容
- html() - 设置或返回所选元素的内容(包括 HTML 标记)
- val() - 设置或返回表单字段的值
下面的例子演示如何通过 jQuery text() 和 html() 方法来获得内容:
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
下面的例子演示如何通过 jQuery val() 方法获得输入字段的值:
$("#btn1").click(function(){
alert("值为: " + $("#test").val());
});
获取属性的值
jQuery attr() 方法用于获取属性值。
下面的例子演示如何获得链接中 href 属性的值:
$("button").click(function(){
alert($("#runoob").attr("href"));
});
二、设置内容和属性
我们将使用前一章中的三个相同的方法来设置内容:
- text() - 设置或返回所选元素的文本内容
- html() - 设置或返回所选元素的内容(包括 HTML 标记)
- val() - 设置或返回表单字段的值
下面的例子演示如何通过 text()、html() 以及 val() 方法来设置内容:
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("RUNOOB");
});
text()、html() 以及 val() 的回调函数
上面的三个 jQuery 方法:text()、html() 以及 val(),同样拥有回调函数。回调函数有两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
下面的例子演示带有回调函数的 text() 和 html():
$("#btn1").click(function(){
$("#test1").text(function(i,origText){
return "旧文本: " + origText + " 新文本: Hello world! (index: " + i + ")";
});
});
$("#btn2").click(function(){
$("#test2").html(function(i,origText){
return "旧 html: " + origText + " 新 html: Hello <b>world!</b> (index: " + i + ")";
});
});
设置属性 - attr()
jQuery attr() 方法也用于设置/改变属性值。
下面的例子演示如何改变(设置)链接中 href 属性的值:
$("button").click(function(){
$("#runoob").attr("href","http://www.runoob.com/jquery");
});
attr() 方法也允许您同时设置多个属性。
下面的例子演示如何同时设置 href 和 title 属性:
$("button").click(function(){
$("#runoob").attr({
"href" : "http://www.runoob.com/jquery",
"title" : "jQuery 教程"
});
});
移除attr:removeAttr, prop
下面的例子删除属性:
$("#runoob").removeAttr("href")
$("#runoob").prop("title")
例子:禁用页面所有的复选框:
$("input[type='checkbox']").prop({
disabled: true
});
禁用和选中所有页面上的复选框,disabled:true表示禁用,checked:true表示选中。
$("input[type='checkbox']").prop("disabled", true);
$("input[type='checkbox']").prop("checked", true);
实例:全部选择、全部取消、反选
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="全选" onclick="SelectAll();">
<input type="button" value="取消" onclick="Cancel();">
<input type="button" value="反选" onclick="Reverse();">
<table>
<tr>
<td><input type="checkbox"></td>
<td>请选择</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>请选择</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>请选择</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>请选择</td>
</tr>
</table>
<script src="jquery.js"></script>
<script>
function SelectAll() {
$("table input").prop("checked",true)
}
function Cancel() {
$("table input").prop("checked",false)
}
function Reverse() {
$("table input").each(
function () {
if($(this).prop("checked")){
$(this).prop("checked",false)
}else{
$(this).prop("checked",true)
}
}
)
}
</script>
</body>
</html>