2

I want to fill a td element by accessing other td s in the same row. How would I access them using jQuery?

In my situation, I have a table, and column 5 is populated by subtracting col 3 from col 4, and returning the result in col 5. I started to do it with a nested loop, but realized, that if I used the .each() on each col 5 td, it would be achievable if I could identify col 3 and 4 using jQuery.

Here is the fiddle.

The section to identify the elements is here:

$('section.techtable td:nth-child(5)').each(function() {
    $(this).append(strinToMonthNumber($(START JQUERY),$(END JQUERY)));
})

I think that I would have to access the parent of $(this), and then the (3rd and 4th) child element?

I am also trying to avoid using span or class attributes on the TH or TD elements.

4

2 回答 2

3

You can select one element (table cell in your case), and then use jQuery.prev() or jQuery.next() to select previous or next sibling element. In native DOM, you could use previousSibling/nextSibling (or previousElementSibling/nextElementSibling in modern browsers to skip non-element nodes) element properties for same purpose.

Based on your code example, something like this:

$('section.techtable td:nth-child(5)').each(function() {
    var cell5 = $(this),
        cell4 = cell5.prev(),
        cell3 = cell4.prev();

    cell5.append(strinToMonthNumber(cell3, cell4)));
})
于 2012-06-10T21:40:44.663 回答
1

Try this:

$('section.techtable tr').each(function() {
    var $cells = $(this).find("td");
    var val = strinToMonthNumber($cells.eq(2).text(),$cells.eq(3).text());
    $cells.eq(4).text(val);
});

Note that the cell indexes are of zero-origin, therefore one less than your 3/4/5. If you already took zero-origin into account, then +1 in each case.

于 2012-06-10T22:46:10.410 回答