更简洁地编写特定的JavaScript声明

3
一个初学者的问题:如何更加简洁地编写以下代码?我感觉违反了DRY原则。
const goToPreviousSection = document.createElement("button")
const goToNextSection = document.createElement("button")

document.body.appendChild(goToPreviousSection)
document.body.appendChild(goToNextSection)
6个回答

2

最合理的做法是创建一个函数。

function makeButton() {
  const btn = document.createElement("button");
  document.body.appendChild(btn);
  return btn;
}

const goToPreviousSection = makeButton(), goToNextSection = makeButton();

这里似乎数组字面量和解构有点毫无意义。 - Bergi
@Bergi 对于创建名为 makeButtons 的函数并以此方式进行解构,我曾经犹豫不决。但后来为了保持简单性而改变了主意,但未更改解构逻辑。也许我应该更新一下,也这样做...顺便说一句,感谢你的帮助,现在我可以回到我的工作里了.. :) - Keith

1

ParentNode.append()

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'));


那么createElement的重复呢?例如,这样是不起作用的:let goToPreviousSection, goToNextSection; goToPreviousSection = goToNextSection = document.createElement("button") - Tzar
请注意,ParentNode.append() 不受 IE 支持。 - Mathias W
@Mamun 谢谢!jo_va的答案正是我在寻找的。 - Tzar

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'))


1

以下是一种更实用的方法,从按钮列表开始,然后使用两个函数makeButton和insertButton进行插入:

const makeButton = () => document.createElement("button")
const insertButton = button => {
  document.body.append(button)
  return button
}

const [goToPreviousSection, goToNextSection] = [
  makeButton(),
  makeButton()
].map(insertButton)


但是您没有分配 goToPreviousSectiongoToNextSection 常量,这些常量稍后在代码中是特别需要的。顺便说一下,标签是不必要的。 - Tzar
感谢您更新代码。但正如我在之前的评论中所写,['Prev', 'Next']是不必要的。您能把它去掉吗? - Tzar
当然,我会将其删除。 - jo_va

1

我认为你原来的4行代码比目前所有的答案都更加清晰优雅。

如果你只打算拥有比你的示例更多的按钮,那么我认为它们是很好的答案。否则不必担心DRY。


0
你可以编写一个名为 appendBtn 的函数。
function appendBtn(){
    const btn = document.createElement("button");
    document.body.appendChild(btn);
    return btn;
}

稍后可以使用返回值执行其他操作,比如改变样式。

let goToPreviousSection = appendBtn();
goToPreviousSection.style.background = "red";

希望这能帮到你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接