简体   繁体   中英

Can someone explain the following javascript code?

In addition to the explanation, what does the $ mean in javascript? Here is the code:

var ZebraTable = {
    bgcolor: '',
    classname: '',
    stripe: function(el) {
        if (!$(el)) return;
        var rows = $(el).getElementsByTagName('tr');
    for (var i=1,len=rows.length;i<len;i++) {
        if (i % 2 == 0) rows[i].className = 'alt';
        Event.add(rows[i],'mouseover',function() { 
ZebraTable.mouseover(this); });
    Event.add(rows[i],'mouseout',function() { ZebraTable.mouseout(this); });
    }
},
mouseover: function(row) {
    this.bgcolor = row.style.backgroundColor;
    this.classname = row.className;
    addClassName(row,'over');
},
mouseout: function(row) {
    removeClassName(row,'over');
    addClassName(row,this.classname);
    row.style.backgroundColor = this.bgcolor;
}
}

window.onload = function() {
ZebraTable.stripe('mytable');
}

Here is a link to where I got the code and you can view a demo on the page. It does not appear to be using any framework. I was actually going through a JQuery tutorial that took this code and used JQuery on it to do the table striping. Here is the link:

http://v3.thewatchmakerproject.com/journal/309/stripe-your-tables-the-oo-way

Can someone explain the following javascript code?

//Shorthand for document.getElementById
function $(id) {
    return document.getElementById(id);
}

var ZebraTable = {
    bgcolor: '',
    classname: '',

    stripe: function(el) {
        //if the el cannot be found, return
        if (!$(el)) return;

        //get all the <tr> elements of the table
        var rows = $(el).getElementsByTagName('tr');

        //for each <tr> element
        for (var i=1,len=rows.length;i<len;i++) {

            //for every second row, set the className of the <tr> element to 'alt'
            if (i % 2 == 0) rows[i].className = 'alt';

            //add a mouseOver event to change the row className when rolling over the <tr> element
            Event.add(rows[i],'mouseover',function() {
                ZebraTable.mouseover(this); 
            });

            //add a mouseOut event to revert the row className when rolling out of the <tr> element
            Event.add(rows[i],'mouseout',function() { 
                ZebraTable.mouseout(this); 
            });
        }
    },

    //the <tr> mouse over function
    mouseover: function(row) {
        //save the row's old background color in the ZebraTable.bgcolor variable
        this.bgcolor = row.style.backgroundColor;

        //save the row's className in the ZebraTable.classname variable
        this.classname = row.className;

        //add the 'over' class to the className property
        //addClassName is some other function that handles this
        addClassName(row,'over');
    },
    mouseout: function(row) {
        //remove the 'over' class form the className of the row
        removeClassName(row,'over');

        //add the previous className that was stored in the ZebraTable.classname variable
        addClassName(row,this.classname);

        //set the background color back to the value that was stored in the ZebraTable.bgcolor variable
        row.style.backgroundColor = this.bgcolor;
    }
}

window.onload = function() {
    //once the page is loaded, "stripe" the "mytable" element
    ZebraTable.stripe('mytable');
}

$在Javascript中并不代表任何含义,但是它是一个有效的函数名,并且几个库将其用作其全部功能,例如PrototypejQuery

From the example you linked to:

function $() {
    var elements = new Array();
    for (var i=0;i<arguments.length;i++) {
        var element = arguments[i];
        if (typeof element == 'string') element = document.getElementById(element);
        if (arguments.length == 1) return element;
        elements.push(element);
    }
    return elements;
}

The $ function is searching for elements by their id attribute.

The code basically sets alternating table rows to have a different CSS class, and adds a mouseover and mouseout event change to a third css class, highlighting the row under the mouse.

I'm not sure if jQuery, prototype or maybe another third party JS library is referenced, but the dollar sign is used by jQuery as a selector. In this case, the user is testing to see if the object is null.

This function loops through the rows in a table and does two things.

1) sets up alternating row style. if (i % 2 == 0) rows[i].className = 'alt' means every other row has its classname set to alt.

2) Attaches a mouseover and mouseout event to the row so the row changes background color when the user mouses over it.

the $ is a function set up by various javascript frameworks ( such as jquery) that simply calls document.getElementById

$ is the so-called "dollar function", used in a number of JavaScript frameworks to find an element and/or "wrap" it so that it can be used with framework functions and classes. I don't recognize the other functions used, so I can't tell you exactly which framework this is using, but my first guess would be Prototype or Dojo . (It certainly isn't jQuery .)

The code creates a ZebraTable "object" in Javascript, which stripes a table row by row in Javascript.

It has a couple of member functions of note:

  • stripe(el) - you pass in an element el, which is assumed to be a table. It gets all <tr> tags within the table (getElementsByTagName), then loops through them, assigning the class name "alt" to alternating rows. It also adds event handlers for mouse over and mouse out.
  • mouseover(row) - The "mouse over" event handler for a row, which stores the old class and background colour for the row, then assigns it the class name "over"
  • mouseout(row) - The reverse of mouseover, restores the old class name and background colour.

The $ is a function which returns an element given either the elements name or the element itself. It returns null if its parameters are invalid (non-existent element, for example)

I believe the framework being used is Prototype, so you can check out their docs for more info

Have a look at the bottom of the article that you have got the code from, you'll see that they say you'll also need prototype's $ function . From article

In your CSS you'll need to specify a default style for table rows, plus tr.alt and tr.over classes. Here's a simple demo, which also includes the other functions you'll need (an Event registration object and Prototype's $ function).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM