doj*_*joX 9 html javascript dom
我想动态创建一些HTML元素(3个html元素),然后将此html代码作为变量中的字符串返回.我不想将以下函数中的HTML代码写入某个div,但是,我想在var中返回它.
function createMyElements(id1,id2,id3){
//create anchor with id1
//create div with id 2
//create xyz with id3
//now return the html code of above created just now
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
Koo*_*Inc 13
您可以使用创建元素document.createElement.创建后,您可以添加属性.如果希望元素显示在文档中,则必须插入到文档的DOM树中.尝试使用此代码:
var body = document.getElementsByTagName('body')[0],
newdiv = document.createElement('div'); //create a div
newdiv.id = 'newid'; //add an id
body.appendChild(newdiv); //append to the doc.body
body.insertBefore(newdiv,body.firstChild) //OR insert it
Run Code Online (Sandbox Code Playgroud)
如果它只是html你想要这是一种方法:
function createmyElements(id1,id2,id3){
return [
'<a href="some link" id="',
id1,
'">linktxt</a>',
'<div id="" ',
id2,
'"></div>',
'<someElement id="',
id3,
'"></someElement>'
].join('\n');
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是创建一个div而不将其注入到DOM树中,并使用DOM方法向其中添加元素.这是一个创建1个元素的函数
function createElementHtml(id,tagname){
var containerdiv = document.createElement('div'),
nwtag = document.createElement(tagname);
nwtag.id = id;
containerdiv.appendChild(nwtag);
return containerdiv.innerHTML;
}
//usage
createElementHtml('id1','div'); //=> <div id="id1"></div>
Run Code Online (Sandbox Code Playgroud)
网址:
<div id="main"></div>
Run Code Online (Sandbox Code Playgroud)
JavaScript:
var tree = document.createDocumentFragment();
var link = document.createElement("a");
link.setAttribute("id", "id1");
link.setAttribute("href", "http://site.com");
link.appendChild(document.createTextNode("linkText"));
var div = document.createElement("div");
div.setAttribute("id", "id2");
div.appendChild(document.createTextNode("divText"));
tree.appendChild(link);
tree.appendChild(div);
document.getElementById("main").appendChild(tree);
Run Code Online (Sandbox Code Playgroud)
使用 documentFragment 而不是直接添加元素的主要原因是执行速度。
在这个大小上没关系,但是当您开始添加数百个元素时,您会很高兴首先在内存中进行:-)
使用 documentFragment,您可以在内存中构建一棵完整的 DOM 元素树,并且直到最后一刻才会影响浏览器 DOM。
否则它会强制浏览器为每个元素更新,这有时会很痛苦。
您可以将 html 构造为一个变量中的字符串,例如
var html = "";
html += "<a id='" + id1 +"'>link</a>";
html += "<div id='" + id1 +"'>div</div>";
// ... and so on
Run Code Online (Sandbox Code Playgroud)
然后你返回变量 html
return html;
Run Code Online (Sandbox Code Playgroud)