我需要在vanilla javascript中创建以下按钮:
<button class="etmkug-14 SuUwW">
<span class="etmkug-16 ctwFJG">Mark All Read</span>
</button>
不确定如何创建和添加范围:
var button = document.createElement('button');
button.setAttribute('class','etmkug-14 SuUwW');
button.setAttribute('style','margin-left: 10px;');
button.setAttribute('id','mark-all-read');
button.addEventListener('click', function(event){
.
.
.
}
var span = document.createElement('span');
span.setAttribute('class','etmkug-16 ctwFJG');
span.innerHTML = 'Mark All Read';
button.appendChild(span); // Is this how it's done????
答案 0 :(得分:1)
是的,它是如何完成的。您只需添加此行document.body.append(button);
var button = document.createElement('button');
button.setAttribute('class','etmkug-14 SuUwW');
button.setAttribute('style','margin-left: 10px;');
button.setAttribute('id','mark-all-read');
var span = document.createElement('span');
span.setAttribute('class','etmkug-16 ctwFJG');
span.innerHTML = 'Mark All Read';
button.appendChild(span);
document.body.append(button);
答案 1 :(得分:1)
如果你感到懒惰,InnerHTML就是你的朋友;抓住一个容器并添加一些HTML。
var container = document.getElementById('container');
container.innerHTML = container.innerHTML + '<button class="etmkug-14 SuUwW"><span class="etmkug-16 ctwFJG">Mark All Read</span></button>';
答案 2 :(得分:0)
let newButton = document.createElement('button');
newButton.setAttribute("id", "myNewButton");
newButton.className = "myClassName";
newButton.innerText = "clickMe";
newButton.addEventListener("click", clickMe);
document.body.appendChild(newButton);
function clickMe(){
console.log("Hi! I am a new Button.");
}