当用户按下按钮时,我尝试添加(和显示)div,我也在使用css网格。我已经在这里看过了,所有的解决方案都建议使用angular js或node js。
我最近(上周)学习了html,css和javascript,我的时间很紧,所以我想知道是否有可能在没有angular js或node js的情况下创建这些div?
发布于 2018-06-20 22:03:56
您可以使用createElement创建HTML元素
它实际上非常简单:
function add() {
// Create element; can be whatever you want, e. g. div, h1, p, img...
var div = document.createElement('div');
// Set some attributes
div.style.width = '200px';
div.style.height = '200px';
div.style.backgroundColor = 'red';
// Append the div to the body
document.body.appendChild(div);
}<button onclick="add()">Add div</button>
发布于 2018-06-20 22:04:48
有很多方法可以做到这一点。
createElement,通常与appendChild和/或insertBefore结合使用:parent.appendChild(document.createElement("div"));
innerHTML来替换父元素的内容:parent.innerHTML = "";
insertAdjacentHTML,同样使用包含HTML的字符串:parent.insertAdjacentHTML("beforeend","");
在MDN's DOM section中有很多需要发现的地方。
发布于 2018-06-20 22:05:46
可以,您可以使用document.createElement
试试这个:
<html>
<head>
<title>Hello World</title>
</head>
<body>
<script>
function CreateDiv(){
var myDiv = document.createElement("DIV"); // Create a <div> node
var myTextNode = document.createTextNode("Hello World"); // Create a text node
myDiv.appendChild(myTextNode); // Append the text
//document.getElementById("myList").appendChild(node); // Append
document.body.appendChild(myDiv);
}
</script>
<input type="button" onclick="CreateDiv();" value="Create div">
</body>
</html>https://stackoverflow.com/questions/50950056
复制相似问题