可以操作HTML元素文本的jQuery对象方法有:$(nodeString).html()、$(nodeString).text()、$(nodeString).val()这三种方法。
1、$(nodeString).html()
用来返回或设置被选择元素的html代码所表示的内容(包括html标签)。html()方法不能使用在表单元素上,应用在多个元素上时,
只读取第一个元素的html内容。
2、$(nodeString).text()
用来读取元素的纯文本内容(包括其后代元素),
text()方法也不能使用在表单元素上,应用在多个元素上时,
将会读取所有选中元素的文本内容。
3、$(nodeString).val()
用来读取表单元素的value值,val()方法只能用在表单元素上,应用在多个元素上时,只能读取第一个表单元素的value值。
示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery对象方法操作html元素内容</title>
<script src="jquery.js" type="text/javascript">
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".btn1").click(function(){
$("div p").html("Hello <b>world!</b>");
});
$(".btn2").click(function(){
alert($("p").text());//把<p>元素中的纯文本内容显示到警告栏中
});
$(".btn3").click(function(){
$(":text").val("Hello 森林卫士!");
});
});
</script>
</head>
<body>
<div >
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</div>
<button class="btn1" >改变p元素的内容</button>
<br/>
<br/>
<p>森林卫士(秋季版)</p>
<button class="btn2" >什么游戏?</button>
<form>
<p>姓名:<input type="text" name="user" value="hello 阿布韦!"/></p>
<button class="btn3" >改变表单的设置值</button>
</form>
</body>
</html>
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery对象方法操作html元素内容</title>
<script src="jquery.js" type="text/javascript">
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".btn1").click(function(){
$("div p").html("Hello <b>world!</b>");
});
$(".btn2").click(function(){
alert($("p").text());//把<p>元素中的纯文本内容显示到警告栏中
});
$(".btn3").click(function(){
$(":text").val("Hello 森林卫士!");
});
});
</script>
</head>
<body>
<div >
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</div>
<button class="btn1" >改变p元素的内容</button>
<br/>
<br/>
<p>森林卫士(秋季版)</p>
<button class="btn2" >什么游戏?</button>
<form>
<p>姓名:<input type="text" name="user" value="hello 阿布韦!"/></p>
<button class="btn3" >改变表单的设置值</button>
</form>
</body>
</html>