www.webdeveloper.com
Results 1 to 2 of 2

Thread: Problem Attaching Handler Functions to Cells in a Table

  1. #1
    Join Date
    Sep 2012
    Posts
    3

    Problem Attaching Handler Functions to Cells in a Table

    Hi,
    I am new to jquery and javaScript. What I am trying to do is create a $(document).ready(function() that uses a for loop to iterate over a table and attach the .click(function() to a column of cells in the table. The onclick function opens a new row below the row that is clicked on. Here is my code:

    //******************************************************************************

    $(document).ready(function() {

    x = document.getElementsByTagName('span');

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

    if ( x[i].className == "initiative" ){

    $(x[i]).click(function(){

    $('tr.vendor' + i).toggle();
    });
    }
    }
    });

    //******************************************************************************

    When I run it the same click function gets attached to all the cells. The code is attaching $('tr.vendor17').toggle(); to all of the cells in the column. Every cell that gets clicked on opens a row beneath the last row (row 17). I am unsure of what the problem is. I have tested the iteration with alert boxes. That all works fine. It has something to do with the onclick callback function itself. Are there any javascript/jquery mavins out there who can explain this to me?

    Thanks in advance for any help that you can give.
    Pete M.

  2. #2
    Join Date
    Nov 2010
    Posts
    1,083
    it's called function closure. I'm not 100% on how it goes for jQuery, but you can try this:

    Code:
    $(document).ready(function() {
    x = document.getElementsByTagName('span');
    for(i=0; i < x.length; i++){
    if ( x[i].className == "initiative" ){ 
    $(x[i]).click(function(i){
    return function() {
    $('tr.vendor' + i).toggle();
    			}
    		})(i);
    	}
    }
    });

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles