jQuery中html()方法用法實例
本文實例講述了jQuery中html()方法用法。分享給大家供大家參考。具體分析如下:
此方法能夠設(shè)置和取得匹配元素的HTML內(nèi)容,原來的內(nèi)容將會被新設(shè)置的內(nèi)容替換。
特別說明:
HTML內(nèi)容就是內(nèi)容中可以包含HTML標簽,并且能夠被瀏覽器渲染。
文本內(nèi)容是先將內(nèi)容中的HTML預(yù)定義字符轉(zhuǎn)換成html字符實體,這樣HTML標簽就不會被渲染。
語法結(jié)構(gòu)一:
此時方法不帶參數(shù)時候是取得第一個匹配元素的html內(nèi)容。
此方法與text()方法沒有參數(shù)用法類似,但是還是有很大區(qū)別:
一.html()方法取得第一個匹配元素的內(nèi)容,而text()方法是取得所有匹配元素包含的內(nèi)容。
二.html()方法取得內(nèi)容html內(nèi)容,而text()方法取得是文本內(nèi)容。
實例代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.dhdzp.com/" />
<title>腳本之家</title>
<style type="text/css">
div
{
height:150px;
width:150px;
background-color:green;
margin-top:10px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
alert($("div").html());
})
})
</script>
</head>
<body>
<div>
<ul>
<li><span>腳本之家歡迎您</span></li>
</ul>
</div>
<button>點擊查看效果</button>
</body>
</html>
以上代碼將返回div元素中的內(nèi)容。
語法結(jié)構(gòu)二:
帶有參數(shù)的時候是設(shè)置所有匹配元素而的html內(nèi)容。
此方法與text()方法帶有參數(shù)的用法類似,但是還是有很大的區(qū)別:
html()方法設(shè)置的是html內(nèi)容,而text()方法設(shè)置的是文本內(nèi)容。
實例代碼:
以下代碼將div中的html內(nèi)容設(shè)置為"<b>我是重新設(shè)置后的內(nèi)容</b>"。
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.dhdzp.com/" />
<title>腳本之家</title>
<style type="text/css">
div
{
height:150px;
width:150px;
background-color:green;
margin-top:10px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div").html("<b>我是重新設(shè)置后的內(nèi)容</b>");
})
})
</script>
</head>
<body>
<div>原來內(nèi)容</div>
<button>點擊查看效果</button>
</body>
</html>
實例二:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.dhdzp.com/" />
<title>腳本之家</title>
<style type="text/css">
div
{
height:150px;
width:150px;
background-color:green;
margin-top:10px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".html").html("<b>好好學(xué)習(xí)</b>");
$(".text").text("<b>好好學(xué)習(xí)</b>");
})
})
</script>
</head>
<body>
<div class="html"></div>
<div class="text"></div>
<button>點擊查看效果</button>
</body>
</html>
通過此實例大家可以觀察一下html內(nèi)容和文本內(nèi)容的區(qū)別。
希望本文所述對大家的jQuery程序設(shè)計有所幫助。
相關(guān)文章
jQuery源碼分析-04 選擇器-Sizzle-工作原理分析
在分析Sizzle源碼之前,先整理一下選擇器的工作原理,先明確一些選擇器中用到的名詞,后邊閱讀時不會有歧義2011-11-11
jquery 構(gòu)造函數(shù)在表單提交過程中修改數(shù)據(jù)
這篇文章主要介紹了jquery 構(gòu)造函數(shù)在表單提交過程中修改數(shù)據(jù)的方法,十分簡單實用,有需要的小伙伴可以參考下。2015-05-05
jquery上傳插件fineuploader上傳文件使用方法(jquery圖片上傳插件)
這篇文章主要介紹了jquery插件fineuploader上傳文件很用方法2013-12-12

