In my app I need to dynamically generate a series hyperlinks. Each
hyperlink's action must be to focus a field in a <form>. I created the
following function to create such a link (the argument is a field
object, e.g. <input>):
function createFieldAnch or(field, linkText)
{
var anchor = document.create Element("a");
anchor.field = field;
anchor.href='ja vascript:this.f ocusField()';
anchor.innerHTM L = linkText;
anchor.focusFie ld = function()
{
var f = this.field;
f.focus();
f.select();
}
return anchor;
}
The link does not work. Debugging shows that the problem is in
'javascript:thi s.focusField()' . The 'this' operator does not refer to
the anchor here (as I expected), but to the window object!
Is there a simple way to get a reference to the anchor in that
context?
I thought up the following 'tricky' solution, which works, but it's
not a very elegant solution:
//General function to implement auto-increments on an object.
function genAutoInc(obj)
{
if (obj.autoIncSee d == null) {
obj.autoIncSeed = 0;
}
obj.autoIncSeed ++;
return obj.autoIncSeed ;
}
//This version assigns a unique ID to the anchor and uses that to
refer to it in the HREF.
function createFieldAnch or2(field, linkText)
{
var anchor = document.create Element("a");
anchor.field = field;
anchor.id = 'dynamicId'+gen AutoInc(field.o wnerDocument);
anchor.href='ja vascript:docume nt.getElementBy Id("'+anchor.i d
+'").focusField ()';
anchor.innerHTM L = linkText;
anchor.focusFie ld = function()
{
var f = this.field;
f.focus();
f.select();
}
return anchor;
}