在没有 jQuery 的情况下添加?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15186706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
prepend without jQuery?
提问by Alosyius
How can i write this without using jQuery?
我如何在不使用 jQuery 的情况下编写它?
$('body').prepend('<div id="idC" style="display: none;" class=""><div id="idA">' + titelN + '</div></div>');
回答by Derek
You should first learn how to create an element without using any library. Basically, there are some method for you to create element and append element to the document. They are createElement
, insertBefore
, appendChild
.
您应该首先学习如何在不使用任何库的情况下创建元素。基本上,有一些方法可以让您创建元素并将元素附加到文档中。它们是createElement
,insertBefore
,appendChild
。
createElement ref: http://www.w3schools.com/jsref/met_document_createelement.asp
insertBefore ref: http://www.w3schools.com/jsref/met_node_insertbefore.asp
appendChild ref: http://www.w3schools.com/jsref/met_node_appendChild.asp
createElement 参考:http: //www.w3schools.com/jsref/met_document_createelement.asp
insertBefore 参考:http: //www.w3schools.com/jsref/met_node_insertbefore.asp
appendChild 参考:http: //www.w3schools.com/jsref /met_node_appendChild.asp
The code below should work for all browser. Try more and learn more.
下面的代码应该适用于所有浏览器。尝试更多并了解更多。
var parent = document.createElement("div");
parent.id = "idC";
parent.style.display = "none";
var child = document.createElement("div");
child.id = "idA";
child.innerHTML = titelN;
parent.appendChild(child);
document.body.insertBefore(parent,document.body.childNodes[0]);
回答by Bergi
There is the insertAdjacentHTML
method, but it does not work in older FF versions:
有insertAdjacentHTML
方法,但它在较旧的 FF 版本中不起作用:
document.body.insertAdjacentHTML('afterbegin', '<div id="idC" style="display: none;" class=""><div id="idA">' + titelN + '</div></div>');