2011年11月9日 星期三

jQuery 進行AJAX時,單獨顯示某dom node內容的方法

因為翻w3school時,不小心翻到jQuery的get() method,才半解決自己之前的疑問--「當我用ajax時,要如何單獨顯示某dom node的內容」…… 結果有bug…… 後來自己研究許久終於連這bug也解決,也就是說「當我用ajax時,要如何單獨顯示某dom node的內容」這問題得到解答了: 下為「a.html」
<!DOCTYPE html>
<html>
<head>
<title>A</title>
</head>

<body>
<!--div-->
The content of the document......
<div id="article" style="background-color: #AAA">
	article
	<div id="nav" style="background-color: #eee">nav</div>
</div>
<!--/div-->
</body>

</html>
下為執行AJAX的「b.html」(這code的目的是要load a.html後顯示#article的內容)
<!DOCTYPE html>
<html>
<head>
<title>B</title>
<script src="jquery-1.7.js"></script>
<script>
	$(document).ready(function(){
		$.ajax({
			url:"a.html", 
			dataType: "html",
			success:function(result){
			var data=$(result)
				$("div").html(data.find("#article").get(0).innerHTML);
			}
		})
	})
</script>

</head>

<body>
<div>AJAX DATA</div>
</body>

</html>
以上得代碼,並不會顯示任何東西(搞笑啊 但是若是把「data.find("#article")」改為data.find("#nav")就能工作……. 研究以後發現,data.find("div").get(0),在裡面會視為"#nav"而非"#article",估計是因為"#article"是最外層吧…… 如果要修正的話,在「a.html」把我特地註解的div顯示(也就是讓最外層要有個 parent node)
<!DOCTYPE html>
<html>
<head>
<title>A</title>
</head>

<body>
<div>
The content of the document......
<div id="article" style="background-color: #AAA">
	article
	<div id="nav" style="background-color: #eee">nav</div>
</div>
</div>
</body>

</html>

沒有留言:

張貼留言