一个初学者的问题:您将如何以更简洁的方式编写以下代码?我觉得自己违反了DRY
原则。
const goToPreviousSection = document.createElement("button")
const goToNextSection = document.createElement("button")
document.body.appendChild(goToPreviousSection)
document.body.appendChild(goToNextSection)
答案 0 :(得分:2)
逻辑上是创建一个函数。
function makeButton() {
const btn = document.createElement("button");
document.body.appendChild(btn);
return btn;
}
const goToPreviousSection = makeButton(), goToNextSection = makeButton();
答案 1 :(得分:1)
ParentNode.append()
可以附加多个节点和字符串,而Node.appendChild()
只能附加一个节点。
您可以使用由append()
插入的appendChild()
以单行显示:
function createButton(txt){
var b = document.createElement("button");
b.textContent = txt;
return b;
}
document.body.append(createButton('Prev'),createButton('Next'));
答案 2 :(得分:1)
您可以创建一个函数来创建元素
function createElem(elemName, txt) {
let elem = document.createElement(elemName);
let content = document.createTextNode(txt);
return elem.appendChild(content);
}
function appendToBody(elem) {
document.body.appendChild(elem)
}
appendToBody(createElem('button', 'Previous'));
appendToBody(createElem('button', 'Next'))
答案 3 :(得分:1)
这是一种更实用的方法,从按钮列表开始,然后使用makeButton和insertButton两个功能进行插入:
const makeButton = () => document.createElement("button")
const insertButton = button => {
document.body.append(button)
return button
}
const [goToPreviousSection, goToNextSection] = [
makeButton(),
makeButton()
].map(insertButton)
答案 4 :(得分:1)
我认为您原来的4行比到目前为止发布的所有答案更清晰,更优雅。
我认为,仅当您计划使用比示例更多的按钮时,它们才是很好的答案。否则不用担心DRY。
答案 5 :(得分:0)
您可以编写一个appendBtn函数
function appendBtn(){
const btn = document.createElement("button");
document.body.appendChild(btn);
return btn;
}
后来使用返回值执行其他操作,例如更改样式,
let goToPreviousSection = appendBtn();
goToPreviousSection.style.background = "red";
希望这会有所帮助。