【问题标题】:Why does updating a variable containing `document.getElementById("text").value` not change the DOM? [duplicate]为什么更新包含 `document.getElementById("text").value` 的变量不会改变 DOM? [复制]
【发布时间】:2020-02-04 10:12:55
【问题描述】:

这是我的代码,我想删除 <textarea>value

<textarea name="text" id="text" cols="50" rows="6" placeholder="inset" required></textarea>
<input type="button" id="btn" value="등록">
<input type="button" id="btn1" value="추가">

JS:

document.querySelector("#btn").addEventListener("click", function(e) {
  var date = document.querySelector("#date");
  var item = document.querySelector("#item");
  var sn = document.createElement("div");
  var sp = document.createElement("div");
  var txt = document.getElementById("text").value;
  date.appendChild(sn);
  item.appendChild(sp);
  date.removeAttribute("id");
  item.removeAttribute("id");
  sn.setAttribute("id", "date");
  sp.setAttribute("id", "item");
  sn.append(today);
  sp.append(txt);
  txt = "";
});

当我编写上面的代码时,我无法删除该值,但在下面的代码中它正在工作。这是为什么呢?

var date = document.querySelector("#date");
  var item = document.querySelector("#item");
  var sn = document.createElement("div");
  var sp = document.createElement("div");
  var txt = document.getElementById("text").value;
  date.appendChild(sn);
  item.appendChild(sp);
  date.removeAttribute("id");
  item.removeAttribute("id");
  sn.setAttribute("id", "date");
  sp.setAttribute("id", "item");
  sn.append(today);
  sp.append(txt);
  document.getElementById("text").value = "";
});

【问题讨论】:

  • 删除(id text) textarea document.getElementById('text').value = ""的文本;

标签: javascript html dom


【解决方案1】:
txt = ""; // This changes the value of variable txt as ""

而,

document.getElementById("text").value = ""; // sets the value of element with id "text" to "".

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-15
    • 2011-01-25
    • 2019-08-19
    • 2019-08-15
    • 2015-03-05
    • 1970-01-01
    • 2019-06-22
    • 2015-01-07
    相关资源
    最近更新 更多