web網(wǎng)頁(yè)是由?html標(biāo)簽一層層組成的起暮,js也可以動(dòng)態(tài)添加對(duì)應(yīng)的標(biāo)簽,比如mate標(biāo)簽会烙、script標(biāo)簽负懦、div標(biāo)簽、img標(biāo)簽等柏腻,動(dòng)態(tài)創(chuàng)建的方法基本都差不多纸厉,下面將簡(jiǎn)單介紹下如何實(shí)現(xiàn)
一:手動(dòng)添加mate標(biāo)簽
function addMeta(name,content){//手動(dòng)添加mate標(biāo)簽
let meta = document.createElement('meta');
? ? meta.content=content;
? ? meta.name=name;
? ? document.getElementsByTagName('head')[0].appendChild(meta);
}
二:手動(dòng)添加script標(biāo)簽
function addScript(src){//手動(dòng)添加script標(biāo)簽
let script=document.createElement("script");
? ? script.type="text/JavaScript";
? ? script.src= src;
? ? document.getElementsByTagName('head')[0].appendChild(script);
}
三:動(dòng)態(tài)添加元素div
function adddiv(pid,html,attr){//動(dòng)態(tài)添加元素div
attr=attr || {};
let parent = document.getElementById(pid);
let div = document.createElement("div");//添加 div
for(let i in attr){//設(shè)置 div屬性
div.setAttribute(i,attr[i]);
}
div.innerhtml = html;
parent.appendChild(div);
}
addDiv("pid","<p>動(dòng)態(tài)添加的div</p>",{"id":"newDiv"});//調(diào)用
攝圖網(wǎng)https://www.wode007.com/sites/73204.html
VJ師網(wǎng)https://www.wode007.com/sites/73287.html
四:動(dòng)態(tài)添加元素img標(biāo)簽
function addImg(pid,src,attr){//動(dòng)態(tài)添加元素img標(biāo)簽
attr=attr || {};
let parent = document.getElementById(pid);
let img = document.createElement("img");//添加 div
for(let i in attr){//設(shè)置 div屬性
img.setAttribute(i,attr[i]);
}
img.src = src;
parent.appendChild(img);
}