在js里動(dòng)態(tài)更改html內(nèi)容時(shí)經(jīng)常會(huì)用到append()/appendTo()和html()方法。
在此記錄下使用區(qū)別。
append()與appendTo()在元素尾部插入內(nèi)容
//語(yǔ)法
$(selector).append(content) //content可包含 HTML 標(biāo)簽,可為函數(shù)
$(content).appendTo(selector) //content可包含 HTML 標(biāo)簽,不可為函數(shù)
使用
//append()
$("p").append(" <b>Hello world!</b>");
$("p").append(function(index){ // 參數(shù)可選,接收選擇器的 index 位置。
return "<b>這個(gè) p 元素的 index 是:" + index + "</b>";
};
//appendTo()
$("<b> Hello World!</b>").appendTo("p");
相同之處
1、插入的內(nèi)容依舊在主體的內(nèi)部結(jié)尾,而不是主體外部。
不同之處:
1、內(nèi)容和選擇器的位置
2、append() 能夠使用函數(shù)來(lái)附加內(nèi)容。
html() 設(shè)置所有匹配元素的內(nèi)容/返回第一個(gè)匹配元素的內(nèi)容
//語(yǔ)法
$(selector).html(content)//content可包含 HTML 標(biāo)簽,為空時(shí)返回元素內(nèi)容,可為函數(shù)
使用
$("p").html("Hello <b>world!</b>");
$("p").html(function(index){// 參數(shù)可選,接收選擇器的 index 位置。
return "這個(gè) p 元素的 index 是:" + index;
});
總結(jié):append()/appendTo()側(cè)重與添加元素內(nèi)容,html()側(cè)重于替換元素內(nèi)容。