Javascript: call function / method of object from onclick event with dynamic argument

I am 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 am getting "function not defined" but can successfully call MyItem.toggle () from the console. I've also tried:

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

      

The anchor must be dynamically created in javascript. How do I call the toggle () method of the MyItem object from a dynamically generated anchor?

ps, I am typing js from memory, so if there are syntax errors I am sorry.

+3


source to share


2 answers


Don't add event handlers and the like. Using DOM Methods

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

      



I really 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();
}

      

+6


source


It won't work. You are trying to use an object as a string. Try the following:



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

      

+1


source







All Articles