This works (in Firefox) …
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="src/myJS.js"></script>
</head>
<body></body>
</html>
Javascript file (called myJS.js for convenience)
window.onload = function()
{
CreateInputTable();
};
CreateInputTable = function()
{
var tbl = document.createElement('table');
var tbo = document.createElement('tbody');
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var ib = document.createElement('input');
ib.setAttribute('type', 'text');
var tdID = "c1"; // Cell reference
if (ib.addEventListener)// all browsers except IE before version 9 - see http://help.dottoro.com/ljeuqqoq.php
{
ib.addEventListener('change', foo, false);
}
else// IE before version 9 - see http://help.dottoro.com/ljeuqqoq.php
{
ib.attachEvent('change', foo, false);
};
td1.appendChild(ib);
tr.appendChild(td1);
var td2 = document.createElement('td');
td2.setAttribute('id', tdID);
td2.appendChild(document.createTextNode("Hello world"));
tr.appendChild(td2);
tbo.appendChild(tr);
tbl.appendChild(tbo);
document.getElementsByTagName('body')[0].appendChild(tbl);
};
function foo (){
if (document.getElementById("c1"))
{
document.getElementById("c1").appendChild(document.createTextNode(" and goodbye"));
}
};
However, I want to pass the cell reference “c1” to the event listener dynamically.
If I understand it correctly, I cant change the call to …
ib.addEventListener('change', foo(tdID), false);
because the parentheses will return the return value of foo, not foo as a function.
However, I can get it to work by changing the declaration of tdID to
this.var tdID = "c1";
… and foo to
function foo (){
if (document.getElementById(tdID))
{
document.getElementById(tdID).appendChild(document.createTextNode(" and goodbye"));
}
};
If I understand it correctly, it works because foo is called within CreateInputTable, which means that it can see the this variables in CreateInputTable.
However, this won’t give me what I want because I want to create a second row with a new value for tdID. The above example seems to simply hard code the cell reference into foo.
How can I dynamically pass the cell reference to foo(in Object Oriented style)?
An elegant way would be this:
Then you can actually write
because the call to
foo(tdID9)will return a function with the right number of arguments and “knows” the correct value for `tdID’ because it is captured in the closure of the inner function.This technique is called currying.