在我的页面上我有:
<div id='something'></div>
我想使用 JS 将这种类型的“按钮”附加到它:
<a href="/news_events/"><span class="picon-p-add-news"></span>Read more news</a>
我尝试使用 document.createElement,但我不确定如何让它不只是作为文本附加。我该怎么做?
最佳答案
像这样,您可以在其中通过函数参数传递元素 ID 和 URL。
<!DOCTYPE html>
<html>
<head>
<script>
function appendButton(elementId, url){
var buttonEl = document.createElement("a");
buttonEl.href = url;
var buttonTextEl = document.createElement("span");
buttonTextEl.className = "picon-p-add-news";
buttonTextEl.innerText = "Read more news";
buttonEl.appendChild(buttonTextEl);
document.getElementById(elementId).appendChild(buttonEl);
}
</script>
</head>
<body>
<div>
<button id="button">Click to add</button>
<div id='something'></div>
</div>
<script>
document.getElementById("button").addEventListener('click', () => appendButton("something", "/news_events/"));
</script>
</body>
</html>
关于javascript - 使用 javascript 向现有 DIV 添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49820106/