OOP javascript - cannot assign onclick event handler on page load

So, I'm trying to create a custom tab system using javascript. However, to reuse the code, I want to write it in OOP style. This is what I still have:

function Tabs()
{

    this.tabArray = new Array(arguments.length);
    this.tabArrayC = new Array(arguments.length);

    for(i=0;i<arguments.length;i++)
    {
        this.tabArray[i] = arguments[i];
        this.tabArrayC[i] = arguments[i]+'_content';
    }

    this.setClickable = setClickable;

    function setClickable()
    {   

        for(i=0;i<this.tabArray.length;i++)
        {

                document.getElementById(this.tabArray[i]).onclick = function()
                {

                    alert(this.tabArray[i]);

                }

        }

    }

}

function init()
{
    tab = new Tabs('tab1','tab2','tab3','tab4');
    tab.setClickable();
}

window.onload = init();

Now here's the deal. I want to assign an onclick event handler to each tab that was passed in the constructor of the Tables class. So later in the code, when I write something like:

<div id="tab1">Tab1</div>
<div id="tab2">Tab2</div>
<div id="tab3">Tab3</div>
<div id="tab4">Tab4</div>

Code that was installed earlier:

document.getElementById(this.tabArray[i]).onclick = function()
{

                    alert(this.tabArray[i]);

}

... will be done. I hope I explained it quite well. Any ideas?

+3
source share
2 answers

There are three problems with your function setClickable( edit : and a problem with how you call init):

  • this , , . ( : this)

  • (, , i), , . , i , . ( : )

  • i, .

:

function setClickable()
{   
    var i;           // <== Declare `i`
    var self = this; // <== Create a local variable for the `this` value

    for(i=0;i<this.tabArray.length;i++)
    {
                                                         // v=== Use a function to construct the handler
        document.getElementById(this.tabArray[i]).onclick = createHandler(i);
    }

    function createHandler(index)
    {
        // This uses `self` from the outer function, which is the
        // value `this` had, and `index` from the call to this
        // function. The handler we're returning will always use
        // the `index` that was passed into `createHandler` on the
        // call that created the handler, so it not going to change.
        return function() {
            alert(self.tabArray[index]);
        };
    }
}

... goreSplatter, Felix , :

window.onload = init();

... init onload. :

window.onload = init;

... init onload.


. "DOM2" "DOM0" onXYZ. addEventListener, , , Internet Explorer ( attachEvent, ). , jQuery, Prototype, YUI, Closure, , ( ).

+6

:

function init()
{
    tab = new Tabs('tab1','tab2','tab3','tab4');
    tab.setClickable();
}

window.onload = init();

window.onload undefined, init() . ,

window.onload = init;

?

+4

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


All Articles