Using 'this' inside a link generated by a javascript object

Javascript is pretty shaky for me and I can't find the answer to this question. I have code line by line

var Scheduler = function(divid,startDate,mode){

    this.setHeader = function(){
          header.innerHTML = '<a href="#" onclick="this.showScheduler(1);">Show</a>';

    }

   this.showScheduler = function period(){

        ...
   }

};

My problem is how do I put onclick in HTML so that it correctly calls the showScheduler function for the corresponding instance of the current scheduler object I'm working with?

+3
source share
6 answers

You should use a framework for this type of thing. If you are not using it, you must declare each instance of the schedule as a global object, and you will need the instance name to call it from the link. Take a look at the following link

http://developer.yahoo.com/yui/examples/event/eventsimple.html

, -

YAHOO.util.Event.addListener(myAnchorDom, "click", this.showScheduler,this,true);

myAnchorDom dom. showScheduler .

+1

, , , , , ( :)):

var Scheduler = function(divid, startDate, mode){
    var that = this;

    this.setHeader = function(){
          header.innerHTML = '<a href="#">Show</a>';
          header.firstChild.onclick = function() { that.showScheduler(1); };
    }

   this.showScheduler = function period(){

        ...
   }
};
+4

innerHTML DOM.

:

header.innerHTML = '<a href="#" onclick="this.showScheduler(1);">Show</a>';

:

var x = this; // create a closure reference
var anchor = document.createElement('a');
anchor.href= '#';
anchor.innerHTML = 'Show';
anchor.onclick = function() { x.showScheduler(1); }; //don't use onclick in real life, use some real event binding from a library
header.appendChild(anchor);

:

"this" , , ( "", , , , , ). ( var x), , .

, addEventListener/attachEvent ( ), , , jquery, JS .

+1

You can add an event handler directly to the header object:

var me = this;

this.setHeader = function(){
          header.innerHTML = '<a href="#" onclick="this.showScheduler(1);">Show</a>';

header.addHandler("click", function(e) { me.showScheduler(1); });
    }

Insite function passed, this will refer to the header element.

0
source
var Scheduler = function(divid, startDate, mode)
{
    var xthis = this;

    this.setHeader = function()
    {
          var lnk = document.createElement("a");
          lnk.addEventListener("click", xthis.showScheduler, false);
          lnk.innerText = "Show";
          lnk.setAttribute('href', "#");
          header.appendChild(lnk);
    }

   this.showScheduler = function period(){

        ...
   }
};
0
source

When using "this" inside the onclick attribute, you are actually referencing the anchor tag object. Try this and see if it works:

this.setHeader = function(){
      header.innerHTML = '<a href="#" onclick="Scheduler.showScheduler(1);">Show</a>';
}
-1
source

Source: https://habr.com/ru/post/1716835/


All Articles