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

字號(hào):


    append()方法在被選元素的結(jié)尾插入指定內(nèi)容,html()方法返回或設(shè)置被選元素的內(nèi)容,下面為大家介紹下兩者的區(qū)別及使用
    append(content):方法在被選元素的結(jié)尾(仍然在內(nèi)部)插入指定內(nèi)容,有很多朋友覺(jué)得append與html差不多,其它從英文意義上append是在原有基礎(chǔ)上增加,而html中是替換當(dāng)前所有內(nèi)容。
    定義和用法
    append() 方法在被選元素的結(jié)尾(仍然在內(nèi)部)插入指定內(nèi)容。
    $(selector).append(content)
    使用函數(shù)來(lái)附加內(nèi)容
    使用函數(shù)在指定元素的結(jié)尾插入內(nèi)容。
    語(yǔ)法
    $(selector).append(function(index,html))
    實(shí)例代碼:
    <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() 方法返回或設(shè)置被選元素的內(nèi)容 (inner HTML)。
    如果該方法未設(shè)置參數(shù),則返回被選元素的當(dāng)前內(nèi)容。
    返回元素內(nèi)容
    當(dāng)使用該方法返回一個(gè)值時(shí),它會(huì)返回第一個(gè)匹配元素的內(nèi)容。
    語(yǔ)法
    $(selector).html()
    設(shè)置所有 p 元素的內(nèi)容:
    $(".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) { //表明注銷(xiāo)成功
    $('#message').html("");
    $("#userlogin>div").show();
    }
    else {
    $('#message').append("<p><strong>注銷(xiāo)失敗,請(qǐng)重新嘗試!</strong></p>");
    }
    });
    });