假设我获得了一个元素引用...
var x=document.getElementById("ID123");
现在我想在动态创建的 html 元素上包含 x 的一些函数...
myWin.document.write("<input type='button' data-doit=????? value='Do It' onclick='window.doit(?????);'/>");
这样函数 doit() 就可以重新创建原始引用 x
function doit()
{
var x = ?????;
}
现在,我通过获取通过 getElementsByTagName 找到的 x 数字索引并将其作为参数传递给 doit() 来完成此操作。
有什么办法可以做到这一点吗?
最佳答案
我可能会将 x
的 ID 传递给 doit()
,这需要 doit()
看起来像这样:
function doit(id) {
var x = document.getElementById(id);
// etc
}
就创建 input
元素而言,有几种方法可以做到这一点。这与您当前的解决方案类似(但非标准):
myWin.document.write('<input ... onclick="doit(' + x.id + ');" />');
标准解决方案是使用 DOM API 创建新的 input
元素:
var input = myWin.document.createElement('input');
input.type = 'button';
// other properties
input.onclick = function () {
doit(x.id);
};
// insert new element
document.getElementById("myform").appendChild(input);
(请注意,在这种情况下插入元素会稍微复杂一些 - 您必须以编程方式找到它在 DOM 中的位置)。
最后,如果您使用 jQuery,您可能会这样做:
var input = $('<input type="button" etc />').click(function () {
doit(x.id);
});
$('#myform').append(input);
关于javascript - 通过动态创建的 html 传递元素引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3664416/