函数中创建的元素未追加到DOM

时间:2018-07-30 20:41:33

标签: javascript html

我在弄清楚为什么我创建的Element无法附加到函数中的DOM时遇到了一些问题。

let startText = document.querySelector('.text-container').innerHTML = "Lets Start.";
let lvlTitle = document.querySelector('.text-container');
let background = document.querySelector('.full-page');
lvlTitle.addEventListener('click', countChangeBackground);
var clicks = 0;

function countChangeBackground() {
  clicks += 1;
  var message = "";
  if (clicks == 1) {
    message = "Test";
    background.style.backgroundColor = "#f81884";
    lvlTitle.style.color = "#f2eee2";
  } else if (clicks == 2) {
    message = "Test2";
    background.style.backgroundColor = "#f5ce28";
    lvlTitle.style.color = "black";
  } else if (clicks == 3) {
    message = "Add Li to ul";

    var ul = document.querySelector('.text-container');
    var li = document.createElement('li');

    li.className = 'text-content';
    li.appendChild(document.createTextNode('New Text'));
    ul.appendChild(li);
    console.log(li);
  } else {
    message = startText;
    background.style.backgroundColor = "#f2eee2";
    lvlTitle.style.color = "black";
  }
  lvlTitle.innerHTML = message;
};
<div class="full-page">
  <div class="click-container">
    <ul class="text-container">
    </ul>
  </div>
</div>

这是一个jsfiddle: Append Li to DOM

2 个答案:

答案 0 :(得分:0)

这是导致您出现问题的行:

lvlTitle.innerHTML = message;

设置innerHTML时,如果该元素内还有其他节点,则它们将被覆盖。

在某些情况下,您需要更改逻辑以仅设置innerHTML。

我在这里更新了您的jsfiddle:http://jsfiddle.net/jepoqd01/

答案 1 :(得分:0)

您正在使用innerHTML覆盖整个容器,而未到达正确的内容文本

请参阅解决方案,添加新变量lvlContainer,获取.text-container,lvlText获取.text-content

let startText = document.querySelector('.text-content').innerHTML = "Lets Start.";
let lvlTitle = document.querySelector('.text-content');
let lvlContainer = document.querySelector('.text-container');
let background = document.querySelector('.full-page');

lvlTitle.addEventListener('click', countChangeBackground);

var clicks = 0;

function countChangeBackground() {
  clicks += 1;
  var message = "";
  if (clicks == 1) {
    message = "Test";
    background.style.backgroundColor = "#f81884";
    lvlContainer.style.color = "#f2eee2";
  } else if (clicks == 2) {
    message = "Test2";
    background.style.backgroundColor = "#f5ce28";
    lvlContainer.style.color = "black";

  } else if (clicks == 3) {
    message = "Add Li to ul";

    var ul = document.querySelector('.text-container');
    var li = document.createElement('li');

    li.className = 'text-content';
    li.appendChild(document.createTextNode('New Text'));
    ul.appendChild(li);
    console.log(li);
  } else {
    message = startText;
    background.style.backgroundColor = "#f2eee2";
    lvlContainer.style.color = "black";
  }
  lvlTitle.innerHTML = message;
};

位于jsfiddle中:http://jsfiddle.net/lucaslimax/7jx194gp/37