为createElement创建函数,该函数接受更多参数

时间:2018-08-21 14:13:28

标签: javascript dom

如果有机会使这段代码更短,我很感兴趣。

let event = document.createElement("div")
event.classList.add("event")

let time = document.createElement("div")
time.classList.add("eventTime")
time.textContent = "something"

let timep = document.createElement("p")
timep.classList.add("timep")

let info = document.createElement("div")
info.classList.add("eventInfo")

let summary = document.createElement("h1")
summary.classList.add("eventSummary")

let organizer = document.createElement("p")

organizer.classList.add("eventOrganizer")

time.appendChild(timep)

info.appendChild(summary)
info.appendChild(organizer)

event.appendChild(time)
event.appendChild(info)
document.getElementById("event").appendChild(event)
<div id="event"> Hello </div>

例如可以用较短的版本写吗

function elementCreation(name, style) {
  return document.createElement(name).classList.add(style)
}
let event = elementCreation("div", "event")
let time = elementCreation("h1", "timeclass"
//and so on
    event.appendChild(time) document.getElementById("event").appendChild(event)
<div id="event"></div>

我尝试执行此功能,但显示错误

  

TypeError:无法读取未定义的属性'appendChild'

没有jquery是否可能?

2 个答案:

答案 0 :(得分:0)

您的elementCreation函数必须返回Node,您试图返回.classList.add结果(未定义)。这段代码有效:

function elementCreation(name, style) {
  let element = document.createElement(name);
  element.classList.add(style);
  return element;
}
let event = elementCreation("div", "event")
let time = elementCreation("h1", "timeclass")
//and so on

event.appendChild(time);
document.getElementById("event").appendChild(event)
<div id="event"></div>

答案 1 :(得分:0)

这是因为classList.add方法不返回任何东西,而这是最后执行的语句。要解决此问题:

function elementCreation(name, style) {
    let event = document.createElement(name);
    event.classList.add(style)
    return event;
}
let event = elementCreation("div", "event")
let time = elementCreation("h1", "timeclass")

event.appendChild(time);
document.getElementById("event").appendChild(event)