更简洁地编写特定的JavaScript声明
一个初学者问题:您将如何以更简洁的方式编写以下代码?我觉得我违反了更简洁地编写特定的JavaScript声明,javascript,ecmascript-6,Javascript,Ecmascript 6,一个初学者问题:您将如何以更简洁的方式编写以下代码?我觉得我违反了DRY原则 const goToPreviousSection = document.createElement("button") const goToNextSection = document.createElement("button") document.body.appendChild(goToPreviousSection) document.body.appendChild(goToNextSection)
DRY
原则
const goToPreviousSection = document.createElement("button")
const goToNextSection = document.createElement("button")
document.body.appendChild(goToPreviousSection)
document.body.appendChild(goToNextSection)
ParentNode.append()
可以附加多个节点和字符串,而Node.appendChild()
只能附加一个节点
您可以使用append()
代替appendChild()
使其具有单行:
函数createButton(txt){
var b=document.createElement(“按钮”);
b、 textContent=txt;
返回b;
}
document.body.append(createButton('Prev')、createButton('Next')代码>合乎逻辑的事情是创建一个函数
function makeButton() {
const btn = document.createElement("button");
document.body.appendChild(btn);
return btn;
}
const goToPreviousSection = makeButton(), goToNextSection = makeButton();
您可以创建一个函数来创建元素
函数createElem(elemName,txt){
让elem=document.createElement(elemName);
让内容=document.createTextNode(txt);
返回元素appendChild(content);
}
功能附件本体(elem){
document.body.appendChild(elem)
}
appendToBody(createElem('button','Previous');
appendToBody(createElem('button','Next'))
您可以编写appendBtn函数
function appendBtn(){
const btn = document.createElement("button");
document.body.appendChild(btn);
return btn;
}
稍后使用返回值执行其他操作,如更改样式
let goToPreviousSection = appendBtn();
goToPreviousSection.style.background = "red";
希望这能有所帮助。这里有一个更实用的方法,从按钮列表开始,然后使用两个函数makeButton和insertButton进行插入:
constmakebutton=()=>document.createElement(“按钮”)
const insertButton=按钮=>{
document.body.append(按钮)
返回按钮
}
常量[goToPreviousSection,goToNextSection]=[
makeButton(),
makeButton()
].map(insertButton)
我认为你原来的4行比目前发布的所有答案更清晰、更优雅
我认为只有当你计划有比你的例子更多的按钮时,它们才是很好的答案。否则不要担心干燥 那么,createElement
的重复又如何呢?例如,这个例子不起作用:let goToPreviousSection,goToNextSection;goToPreviousSection=goToNextSection=document.createElement(“按钮”)
注意IE不支持ParentNode.append()
。@Mamun谢谢jo_va
的答案正是我想要的。但是您没有指定goToPreviousSection
和goToNextSection
常量,这是代码后面特别需要的。顺便说一下,标签是不必要的。谢谢更新代码。但正如我在前面的评论中所写的那样,['Prev','Next']
是不必要的。你能把它删掉吗?当然,我会删除它。数组文字和解构在这里似乎有点毫无意义。@Bergi是的,我对创建一个名为makeButtons
的函数有两个想法,然后用这种方式解构。但后来我改变了主意,让它更简单,但没有改变解构逻辑。我可能应该更新,并添加这样的方式太。。。另外,干杯,我现在可以回到两周前了……)