Forum Moderators: open
I have an object from a 3rd-party library. I'm using a function like:
function addHtml(object)
{ object.html += '<a href="javascript:void(0)" onclick="object.close();">Close Object</a>';
}
It adds some html to the objects html (which is displayed later). The problem of course is that object.close(); will not work, because object is just a local variable in my function and not known globally. In fact there can be many of these objects, so I cannot put the object just in a global variable.
So how can I add a reference to the object in my onclick?
... onclick="object.close();" ...
becomes
... onclick="function(){object.close();}" ...
... onclick=function(){object.close();} ...
I read a bit about javascript closures and the use of "this"-pointers, and I think your solution unfortunatly
could only work if you use something like:
link.onclick = function(){object.close};
But i couldn't use that because the tooltip ist not yet defined, so I can't get a DOM-Object of my link.
But in inline event registration, it doesn't seem possible. I tried all your solutions but always gets "syntax error" on clicking.
Can you share the snippet that renders/inserts the .html value? Also, can you share more info about .close() and what it does and how it ought to be called currently?
I read a bit about javascript closures and the use of "this"-pointers, and I think your solution unfortunatly
could only work if you use something like:link.onclick = function(){object.close};
But i couldn't use that because the tooltip ist not yet defined, so I can't get a DOM-Object of my link.
But in inline event registration, it doesn't seem possible. I tried all your solutions but always gets "syntax error" on clicking.
function addHtml(object) {
var link = document.createElement('a');
link.href="#";
link.innerHTML = "Close Object";
link.onclick = function () { object.close(); };
object.appendChild(link);
}
That would be correct. The problem you are having is that the only reference you can make when setting an onclick via a string is 'this' which will refer to the current object only, in this case the link that is being added.
Unfortunatly, this.parentNode gives a DOM-object and not a Javascript-object, on which I have to call the method. And I couldn't find a way to translate one into the other.
Can you share the snippet that renders/inserts the .html value? Also, can you share more info about .close() and what it does and how it ought to be called currently?