创建元素的回调函数返回具有空innerHTML的元素

时间:2020-07-02 16:21:12

标签: javascript callback dom-events innerhtml

我有一个函数,可以创建带有按钮的li元素。但是,当我通过eventListener调用它时,返回创建的元素只是一个没有innerHTML内容的列表。

发生了什么以及如何解决?
这是我的JS脚本:

const inputField = document.querySelector("input.inputField");
const addToList = document.querySelector("input.addToList");
const list = document.querySelector("div.list");

createTodo = () => {
  var li = document.createElement("li");
  let up = "<button class='up'>Up</button>";
  li.innerHTML += up;
  let down = "<button class='down'>Down</button>";
  li.innerHTML += down;
  let remove = "<button class='remove'>Remove</button>";
  li.innerHTML += remove;
  return li;
};

addToList.addEventListener("click", () => {
  let todo = inputField.value;
  var li = createTodo();
  console.log(li);
  li.textContent = todo;
  list.appendChild(li);
  inputField.value = "";
});

1 个答案:

答案 0 :(得分:1)

问题在于,这样做时,您正在破坏library(hts) library(rlist) #forecast grouped time series by custom function ally_df <- aggts(htseg1) %>% as.data.frame forecast_list <- apply(ally_df, 2, function(x){x %>% auto.arima %>% forecast(h = 12)}) ally_fitted <- lapply(forecast_list, function(x){x$fitted %>% as.data.frame}) %>% list.cbind colnames(ally_fitted) <- colnames(ally) ally_forecast <- lapply(forecast_list, function(x){x$mean %>% as.data.frame}) %>% list.cbind colnames(ally_forecast) <- colnames(ally) #create weights for reconciliation recomb_approaches <- c("wls", "ols", "nseries", "bu") recomb_approach <- recomb_approaches[1] if(recomb_approach == "bu"){ weights <- c(rep(0, ncol(ally_df)-ncol(htseg1$bts)), rep(1, ncol(htseg1$bts))) }else if(recomb_approach == "ols"){ weights <- NULL }else if(recomb_approach == "wls"){ tmp.resid <- ally_df - ally_fitted weights <- 1/colMeans(tmp.resid^2, na.rm = TRUE) }else if(recomb_approach == "nseries"){ # A function to calculate No. of groups at each level Mlevel <- function(xgroup) { m <- apply(xgroup, 1, function(x) length(unique(x))) return(m) } # A function to get the inverse of row sums of S matrix InvS4g <- function(xgroup) { mlevel <- Mlevel(xgroup) len <- length(mlevel) repcount <- mlevel[len]/mlevel inv.s <- 1/unlist(mapply(rep, repcount, mlevel, SIMPLIFY = FALSE)) return(inv.s) } weights <- InvS4g(htseg1$groups) } ally_forecast_recombined_df <- combinef(ally_forecast , nodes = get_nodes(htseg1) , weights = weights , algorithms = "lu" , keep = "bottom" , parallel = TRUE , num.cores = cores ) 中的现有元素节点:

li

相反,您可以使用li.textContent = todo; 附加新的文本节点而不会丢失元素节点。

.insertAdjacentText()

此外,通常将li.insertAdjacentText("beforeend", todo); +=一起使用也会引起问题。在您的代码中还算不错,但是有更好的方法,例如使用.innerHTML

并且多次插入似乎比所需的更为冗长。我会这样做:

.insertAdjacentHTML()

然后为什么不让您的函数接收const createTodo = () => { const li = document.createElement("li"); li.insertAdjacentHTML("beforeend", ` <button class='up'>Up</button> <button class='down'>Down</button> <button class='remove'>Remove</button> `; return li; }; 文本作为参数呢?然后,您可以使用字符串插值使其变得非常简单:

todo