jQuery中的html()和val()和text()的区别

html():返回匹配的元素集合中的 HTML 内容。注意:该方法仅返回第一个匹配元素的内容。

 

html(content):设置匹配的元素集合中的 HTML 内容。注意:该方法设置所有匹配元素的内容。

 

text()返回匹配元素的内容    注意:它不会获取到放在该元素下面的html标签下的内容。只会获取到纯文本。

 

text(content)设置匹配元素的内容        注意:工作方式与 html() 类似,但是会对标签进行转义,也就是将html标签按照文本输出。

 

val()返回匹配元素的值        注意:该方法大多用于 input 元素。因为input元素有value属性对应的值。该方法仅返回第一个匹配元素的值。

val(content)设置匹配元素的值                 注意:该方法设置所有匹配元素的值。

 

代码
html代码:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> jQuery中的html()和val()和text()的区别.html </title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(
function() {
$(
"button#html1").click(function() {
// alert($("#p1").html());// 空
alert($("#p4").html());// I am fourth paragraph too!

//alert($("div#myDiv").html());
/*返回:
<p id="p1">I am first paragraph!</p>
<p id="p2">I am second paragraph!</p>
<p id="p3">I am third paragraph too!</p>
*/
});
$(
"button#html2").click(function() {
$(
"#p2").html($("#p2").html() + " 点击后面的超链接" + "<a href='http:www.g.cn'>Google</a>");
});

$(
"button#text1").click(function() {
alert($(
"#p3").text());// 返回:I am fourth paragraph too!
//alert($("#p1").text());// 效果与alert($("#p1").html());一样
//alert($("div#myDiv").text());
/*返回:
I am first paragraph!
I am second paragraph!
I am third paragraph too!
I am fourth paragraph too!

*/
});
$(
"button#text2").click(function() {
$(
"#p3").text("将不再出现Google超链接" + "<a href='http:www.g.cn'>Google</a>将以纯文本出现");
});

$(
"button#val1").click(function() {
alert($(
"input").val());// some value
});
$(
"button#val2").click(function() {
$(
"input").val("changed value");
});
});
</script>
</head>

<body>
<div id = "myDiv">
I am pure text!!!
<p id = "p1">
<h1>I am first paragraph!</h1>
</p>

<p id = "p2">
I am pure text too!!!
<h2>I am second paragraph!</h2>
</p>

<p id = "p3">
I am another pure text!!!
<h3>I am third paragraph too!</h3>
</p>
<p id = "p4">I am fourth paragraph too!</p>

<input type ="text" value="some value" />
</div>

<button id = "html1">html()</button><br/>
<button id = "html2">html(content)</button><br/>

<button id = "text1">text()</button><br/>
<button id = "text2">text(content)</button><br/>

<button id = "val1">val()</button><br/>
<button id = "val2">val(content)</button><br/>
</body>
</html>

 


  


posted @ 2010-12-18 14:47  meng72ndsc  阅读(491)  评论(0编辑  收藏  举报