Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  68] [ 1]  / answers: 1 / hits: 18451  / 12 Years ago, thu, january 31, 2013, 12:00:00

I'm trying to do this:



<script>
var MyItem;

MyItem = new myobj('testobj');

function myobj(id)
{
var _id = id;

this.toggle = function()
{
...
}

function draw()
{
document.body.innerHTML += <a onclick=' + MyItem + .toggle();'>link</a>;
}

draw();

}
</script>


I get function is not defined, but can invoke MyItem.toggle() from console successfully. I've also tried:



document.body.innerHTML += <a onclick='(function(){ + MyItem + .toggle();})()'>link</a>;


The anchor has to be dynamically created in javascript. How do I invoke the MyItem object method toggle() from the dynamically created anchor?



ps, I'm typing js from memory, so if there are syntax errors I apologise.


More From » object

 Answers
9

Do not add event handlers and elements like that. Use DOM methods



var anchor = document.createElement(a);
anchor.innerHTML = link;
anchor.onclick = function(){ MyItem.toggle(); };
document.body.appendChild(anchor);


I actually think you are after something like this



var MyItem;

MyItem = new myobj('testobj');

function myobj(id) {
var that = this;
this.toggle = function () {
alert(id);
}
function draw() {
var anchor = document.createElement(a);
anchor.innerHTML = link;
anchor.onclick = function () {
that.toggle();
};
document.body.appendChild(anchor);
}
draw();
}

[#80509] Tuesday, January 29, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliano

Total Points: 381
Total Questions: 109
Total Answers: 93

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
emiliano questions
;