Lets say that I have a element reference obtained ala...
var x=document.getElementById("ID123");
Now I want to include some function of x on a dynamically created html element ala...
myWin.document.write("<input type='button' data-doit=????? value='Do It' onclick='window.doit(?????);'/>");
so that function doit() can recreate the original reference x
function doit()
{
var x = ?????;
}
Right now I'm doing this by obtaining a numeric index of x as found via getElementsByTagName and passing that as a parameter to doit().
Is there some way to do this?
I would probably pass the ID of x
to doit()
, which would require doit()
to look something like this:
function doit(id) {
var x = document.getElementById(id);
// etc
}
As far as creating the input
element goes, there a couple of ways to do this. This is similar to your current solution (but non-standard):
myWin.document.write('<input ... onclick="doit(' + x.id + ');" />');
The standard solution is to create your new input
element using the DOM API:
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);
(Note that inserting the element is a little more complicated in this situation - you have to programmatically find its location in the DOM).
Finally, if you're using jQuery, you might do something this:
var input = $('<input type="button" etc />').click(function () {
doit(x.id);
});
$('#myform').append(input);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.