使用JavaScript DOM创建可编辑的文本字段

时间:2016-05-23 11:31:48

标签: javascript dom

我无法使用JavaScript创建可编辑的文本字段,我发现了一些要编辑的功能,但我不明白是否可以将标题从高中编辑为< strong>初中,由函数createTextNode

创建

我的疑问尤其在于使用指令addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));添加事件来编辑文本字段,运行代码片段以查看结果

try the fiddle

var school = new School(1);

function School(id) {
  this.id = id;
  Unload_School();

  function Unload_School() {

    var div = document.createElement("div");
    div.id = "school";

    var h1 = document.createElement("h1");
    h1.id = "h1";
    h1.style.color = "red";

    var title = document.createTextNode("High School");
    h1.appendChild(title);

    // I use here but not work
    addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));

    var h3 = document.createElement("h3");
    h3.style.color = "blue";

    var subtitle = document.createTextNode("List Of Students:");
    h3.appendChild(subtitle);

    div.appendChild(h1);
    div.appendChild(h3);

    document.body.appendChild(div);
  };
}

function addEvent(obj, evType, fn) {
  try {
    obj.addEventListener(evType, fn, false);
  } catch (e) {}
  try {
    obj.attachEvent("on" + evType, fn);
  } catch (e) {}
}

function edit(param) {
  var elem = param;
  var input = document.createElement("input");
  input.setAttribute("type", "text");
  input.setAttribute("value", elem.firstChild.nodeValue);
  removeChildren(elem);
  elem.appendChild(input);
  input.focus();
  input.select();
  addEvent(input, "blur", function() {
    removeChildren(elem);
    elem.appendChild(document.createTextNode(input.value));
  });
}

function removeChildren(param) {
  for (var i = 0, elem; elem = param.childNodes[i]; i++) {
    elem.parentNode.removeChild(elem);
  }
}
#school {
  display: inline-table;
  vertical-align: middle;
  text-align: left;
}

#h1 {
  font-size: 50px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans - serif;
}
<!DOCTYPE html>
<html lang="pt-PT">

<head>
  <meta charset="UTF-8">
  <title>High School</title>
</head>

<body>
  <div id="school"></div>
</body>

</html>

2 个答案:

答案 0 :(得分:1)

将您的代码从addEvent(getElementById("h1"), "click", new Function("edit(this)"));更改为addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));。此外,没有名为h1的ID。

答案 1 :(得分:1)

经验法则:创建元素时,在将元素附加到DOM之前不要查找元素。

check this working fiddle

 div.appendChild(h1);
 div.appendChild(h3);
 document.body.appendChild(div);

只有在追加所有元素后,才应搜索元素。

 addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));