gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:34:28 25 4
gpt4 key购买 nike

我在使用 JavaScript 创建可编辑文本字段时遇到问题,我找到了一些可以编辑的函数,但我不明白是否可以编辑高中的标题> 到由函数 createTextNode 创建的 Middle School

我的疑问尤其是使用指令 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>

最佳答案

将代码从 addEvent(getElementById("h1"), "click", new Function("edit(this)")); 更改为 addEvent(document.getElementById(") h1"), "点击", new Function("edit(this)"));.而且也没有名为 h1 的 ID。

关于javascript - 使用 JavaScript DOM 创建可编辑文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37389850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com