JavaScript addEventListener 在单击时添加文本框?
我需要能够单击一些文本(id =“txt”)并触发一个事件,用文本框替换该文本;目前我有这段代码:
var myTxt = document.getElementById("txt");
myTxt.addEventListener("click", name1Click, false);
function textclick()
{
var removeMe = document.getElementById("txt");
var root = document.body;
root.removeChild(removeMe);
var addMe = document.createElement("input");
addMe.setAttribute("type","text");
addMe.setAttribute("id","i");
root.appendChild(addMe);
}
这不起作用,但是有什么想法吗?
I need to be able to click on some text (id="txt") and fire an event which replaces that text with a textbox; currently I have this code:
var myTxt = document.getElementById("txt");
myTxt.addEventListener("click", name1Click, false);
function textclick()
{
var removeMe = document.getElementById("txt");
var root = document.body;
root.removeChild(removeMe);
var addMe = document.createElement("input");
addMe.setAttribute("type","text");
addMe.setAttribute("id","i");
root.appendChild(addMe);
}
This is not working, however, any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您在此处发布的代码中,您的 eventListener 正在调用
name1Click
,但您的函数名为textclick
。当你解决这个问题时,它似乎在这里工作: http://jsfiddle.net/jfriend00/55mQq/。
您可能需要注意,旧版本的 IE 不支持
addEventListener()
(您必须使用attachEvent()
代替)。In the code you have posted here, your eventListener is calling
name1Click
, but your function is namedtextclick
.When you fix that, it seems to work here: http://jsfiddle.net/jfriend00/55mQq/.
You may want to note that
addEventListener()
is not supported in older versions of IE (you have to useattachEvent()
instead).在您的代码中:
您在 addEventListener 中添加一个名为 name1Click 的函数,但您的函数名为 textclick。修复这个问题,它就“有效”
另外:
removeMe 元素可能并不总是 body 的子元素,因此您可以更一般地删除它:
但是可以替换节点比删除,见下文。
setAttribute 方法在某些浏览器中存在错误,如果不需要,最好避免使用。对于标准 DOM 属性,只需直接设置属性:
您可以只使用一个操作并一般替换第一个节点,而不是删除一个节点并插入另一个节点:
In your code:
You are adding a function named name1Click in addEventListener, but your function is called textclick. Fix that and it "works"
Also:
It is likely that the removeMe element won't always be a child of the body, so you can remove it more generically with:
But the node can be replaced rather than removed, see below.
The setAttribute method is buggy in some browsers and better avoided if not needed. For standard DOM properties, just set the property directly:
Rather than removing one node and inserting another, you can just use one operation and replace the first one generically: