开发者

jQuery: specifiying the index of a child <td> in a row's onclick function

I have click function for a tabl开发者_运维技巧e row which needs to pass the content of the first two tds in the row.

// Assign a click handler to the rows
$('#supportTables1 tr').click(function ()
{
    var firstTd = $(this).find('td').html();
    //need to get the next td.  below line doesn't work.
    var secondTd = $(this).find('td')[1].html();
    window.open('snglContactList.php'+'?search_word='+firstTD+'?list_name=secondTd);
});

I can get the first td just fine, but I'm stumped on what I'm sure is the profoundly simple matter of accessing the second td (I've tried diferrent methods of setting it's index).


The array notation [1] returns a DOM element, not a jQuery object, so you can't use .html() (a jQuery method) on it. Use the jQuery function .eq() to get the elements instead:

  // Assign a click handler to the rows
  $('#supportTables1 tr').click(function ()
  {
        var firstTd = $(this).find('td').eq(0).html();
        var secondTd = $(this).find('td').eq(1).html();
        window.open('snglContactList.php'+'?search_word='+firstTD+'?list_name='+secondTd);
  });


$(this).find('td') will return all <td> within the clicked row. You can use the eq(idx) method to get ones at a particular index:

$('#supportTables1 tr').click(function ()
{
    var tds = $(this).find('td');
    var firstTd = tds.eq(0).text();
    var secondTd = tds.eq(1).text();
    window.open('snglContactList.php'+'?search_word='+firstTD+'?list_name='+secondTd);
});

Working example here (with alerts rather than window.open...):

http://jsfiddle.net/E5Z5V/


Table rows have their own collection of the cells they contain, which is accessed by the cells property.

Do this:

var firstTd = this.cells[ 0 ].innerHTML;
var secondTd = this.cells[ 1 ].innerHTML;

Or of you insist on a jQuery solution, do this:

var firstTd = $(this.cells[ 0 ]).html();
var secondTd = $(this.cells[ 1 ]).html();

Example: http://jsbin.com/ivabu4/

Note that the first version is fastest because it accesses properties directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜