【发布时间】:2017-02-04 19:22:16
【问题描述】:
例如,当用户单击按钮时,我想使用 JS 在我的网站上的 div 内创建一个带有 id 的 HTML 元素。
我怎样才能做到这一点?
【问题讨论】:
-
这个问题已经被问过很多次了,在谷歌上快速搜索一下就会找到这个问题:stackoverflow.com/questions/9422974/createelement-with-id
标签: javascript html
例如,当用户单击按钮时,我想使用 JS 在我的网站上的 div 内创建一个带有 id 的 HTML 元素。
我怎样才能做到这一点?
【问题讨论】:
标签: javascript html
window.onload=function(){//if the page is loaded
var button=document.getElementById("buttonone");//get your button #buttonone or some other id
button.onclick=function(){
var div=document.createElement("div");
div.id="test";
document.body.appendChild(div);
};
};
我不解释它,因为它是自我解释......
【讨论】:
id,这是不允许的。
你可以通过javascript的createElement函数来实现这个
var btn = document.createElement("DIV"); // Create a <div> element
btn.id="dynamic_id"
document.body.appendChild(btn); // Append <button> to <body>
【讨论】:
你可以像这样使用document.createElement:
var myNewDiv = document.createElement('div');
myNewDiv.id = "your-id";
这将创建一个<div id="your-id">
如果您想在用户单击按钮时插入它,则可以将函数绑定到该按钮:<button onClick="createMyDiv()">Click me</button>
然后在你的javascript中:
function createMyDiv(){
var myNewDiv = document.createElement('div');
myNewDiv.id = "your-id";
// Now you insert it
var parentDiv = document.getElementById('target-div');
parentDiv.appendChild(myNewDiv);
}
【讨论】:
像这样使用document.createElement():
// Counter that will change with each new element so no
// two elements will have the same ID
var counter = 1;
// function that can be called whenever a new element is needed
function makeElement(elementType){
// Create a new element of the type passed in to the function
// This can be hard-coded of course, but is shown this way
// to show how this one function can be reused to make any kind of new element
var newElem = document.createElement(elementType);
// Set the id using the counter value and then increase the counter
newElem.id = elementType + counter++;
// Set the content of the element. Dependingn on the type of element being created
/// other properties would need to be set (i.e. href for <a>, src for <img>, etc.)
newElem.textContent = "I'm a new " + elementType + " with an ID of " + newElem.id;
// Add the element to the document.
// This can be inserted at any specific spot in the document you like.
document.body.appendChild(newElem);
}
// Run the function several times to create various types of elements,
// each with different id's.
makeElement("div");
makeElement("span");
makeElement("h1");
makeElement("p");
【讨论】:
<html>
<head>
<script type="text/javascript">
function createelement() {
document.body.innerHTML += '<div id="yourid">Your Element</div>';
}
</script>
</head>
<body>
<button onclick="createelement()">Create Element</button>
</body>
</html>
【讨论】:
首先,您必须获得容器的引用。
然后,使用 createElement() 创建一个新元素并设置这个新创建元素的 id。
最后,使用 appendChild 将该元素添加到您的容器中()。
const container = document.getElementById('myContainer');
const el = document.createElement('span');
el.id = 'myId';
container.appendChild(el);
【讨论】:
id,这是不允许的。