创建新的HTML元素时,Javascript功能不起作用 [英] Javascript function doesn't work when creating a new HTML element
本文介绍了创建新的HTML元素时,Javascript功能不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的HTML:
My HTML:
<table id="laboral">
<tr>
<td><input type="text" name="start"/></td>
<td><input type="text" name="end"/></td>
<td><textarea name="desc"></textarea></td>
<td><button type="button" onclick="saveRow(this);"> + </button></td>
</tr>
</table>
当我按下 +
按钮时,我创建与第一行完全一致,但 onclick
事件不起作用:
When I press the +
button I create a new row exactly as the first one, but the onclick
event doesn't work:
以下是代码保存值并创建2 输入
s和 textarea
:
Here's the code for saving the values and create the 2 input
s and the textarea
:
var button = document.createElement("button");
button.type = "button";
button.setAttribute("onclick", "saveRow(this);")
button.innerHTML = "+";
var btn = tr.insertCell(3);
btn.appendChild(button);
如果我使用Firefox检查结果,可以看到第一个按钮和新生成的码。但是生成的不起作用。
If I examine the result with Firefox I can see that the first button and the new generated have the same code. But the generated doesn't work.
推荐答案
与其为您可能添加的所有按钮定义事件处理程序,它可能是更有效地推迟到桌子上。在这种情况下,你可以这样做:
Rather than define an event handler for all the buttons you may add, it may be more efficient to defer it to the table. In this case, you'd do this:
// this script should be placed after the table on the page, or deferred in some way
document.getElementById('laboral').onclick = function(e) {
e = e || window.event;
var elem = e.srcElement || e.target;
if( !elem.tagName) elem = elem.parentNode;
if( elem.tagName == "BUTTON") {
var tr = elem;
// find the row that contains the button
while(tr.tagName != "TR") tr = tr.parentNode;
tr.parentNode.insertBefore(tr.cloneNode(true),tr.nextSibling);
}
};
完成^ _ ^
这篇关于创建新的HTML元素时,Javascript功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文