admin管理员组

文章数量:1425859

I'm trying to do a custom tabs system using JavaScript. However, in order to reuse the code I want to write it in OOP style. This what I have so far:

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 the onclick event handler to every tab that has been passed in Tabs 'class' constructor. 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>

The code which has been set up earlier:

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

... would be executed. I hope I explained that well enough. Any ideas?

I'm trying to do a custom tabs system using JavaScript. However, in order to reuse the code I want to write it in OOP style. This what I have so far:

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 the onclick event handler to every tab that has been passed in Tabs 'class' constructor. 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>

The code which has been set up earlier:

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

... would be executed. I hope I explained that well enough. Any ideas?

Share Improve this question edited Jan 6, 2023 at 11:40 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jan 11, 2011 at 11:16 PavelPavel 5,35310 gold badges35 silver badges48 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

There are three issues with your setClickable function (edit: and an issue with how you're calling init):

  1. this will have a different meaning within the event handler you're generating than you expect. (More here: You must remember this)

  2. A closure (a function that closes over data like your i variable) has an enduring reference to the variable, not a copy of its value. So all of the handlers will see i as of when they run, not as of when they're created. (More here: Closures are not plicated)

  3. You're not declaring i, and so you're falling prey to the Horror of Implicit Globals.

Here's one way you can address those:

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's not going to change.
        return function() {
            alert(self.tabArray[index]);
        };
    }
}

...and as goreSplatter and Felix point out, this line:

window.onload = init();

...calls the init function and uses its return value to assign to onload. You mean:

window.onload = init;

...which just assigns init to the onload event.


Off-topic: You might consider using the newer "DOM2" mechanisms for attaching event handlers instead of the old "DOM0" way of using the onXYZ properties and attributes. The new way is called addEventListener, although sadly Internet Explorer has only recently added that (but it has attachEvent which is very similar). If you use a library like jQuery, Prototype, YUI, Closure, or any of several others, they'll smooth out those differences for you (and provide lots of other helpful stuff).

Problematic:

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

window.onload = init();

In this case, window.onload will be undefined, since init() returns nothing. Surely you meant

window.onload = init;

?

本文标签: OOP JavaScriptcan39t assign onclick event handler on page loadStack Overflow