jquery append()方法與html()方法的區別及使用介紹,jqueryappend

來源:互聯網
上載者:User

jquery append()方法與html()方法的區別及使用介紹,jqueryappend

append(content):方法在被選元素的結尾(仍然在內部)插入指定內容,有很多朋友覺得append與html差不多,其它從英文意義上append是在原有基礎上增加,而html中是替換當前所有內容。

定義和用法

append() 方法在被選元素的結尾(仍然在內部)插入指定內容。
$(selector).append(content)

使用函數來附加內容
使用函數在指定元素的結尾插入內容。

文法

$(selector).append(function(index,html))

執行個體代碼:

<script src="/jquery.min.js" type="text/javascript"></script> <style> .imgFocus{border: 1px solid #eee;} </style> <p> </p> <script type="text/javascript"> var showimg = "<div class='imgFocus'>123456</div>"; $("p").append(showimg); </script>

html() 方法返回或設定被選元素的內容 (inner HTML)。

如果該方法未設定參數,則返回被選元素的當前內容。
返回元素內容
當使用該方法返回一個值時,它會返回第一個匹配元素的內容。

文法

$(selector).html()

設定所有 p 元素的內容:

$(".btn1").click(function(){ $("p").html("Hello <b>world</b>!"); });

指定元素中清空

$("a[href$='logout.asp']").click(function(event) { event.preventDefault(); $.get("/xxlr/Logout.asp","",function(data, textStatus) { if (data == 1) { //表明登出成功 $('#message').html(""); $("#userlogin>div").show(); } else { $('#message').append("<p><strong>登出失敗,請重新嘗試!</strong></p>"); } }); });

jQuery中html(“xxx”)與append("xxx")有什不同與不同,是不是都是在頁面上新增內容?

當然不一樣了,append是追加,html是完全替換
比如<p id="1"><p>123</p></p>
$("#1").html("<span>456</span>");
結果是:<p id="1"><span>456</span></p>

$("#1").append("<span></span>");
結果是:<p id="1"><p>123</p><span>456</span></p>
 
jquery中 怎 使用 append() 方法 新添加的元素? $('#id')html()取不到值?

.append( content )
一個簡單的例子
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; }
</style>
<script src="code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<p>I would like to say: </p>
<script>
$("p").append("<strong>Hello</strong>");
</script>

</body>
</html>

=========================================
我本地試了一下,這樣可以取到值
<div id="con"></div>
<div id="result"></div>
<script>
$("#con").append("<div id='hello'>Hello</div>");
$("#result").html($("#hello").html());
</script>

你可以看到有兩個Hello
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.