简体   繁体   中英

Using JQuery .append() to dynamically change table layout

I am using an HTML table but I want to dynamically change the layout of the table based on the browser size. My basic code looks like this:

<tr>
  <td class="row">E1</td>
  <td class="row">E2</td>
  <td class="row">E3</td>
  <td class="lastRow">E4</td>
</tr>

Then the JQuery should calculate the number of rows and insert row-breaks accordingly. My JQuery looks like this for now:

$('td.row').append('</tr><tr>');

Yet, its still displaying all the elements on one line. Any idea why?

This is a perfect place to use fluid CSS layouts.

Instead of writing lots of crazy Dom-manipulating javascript, simply replace your TD tags with divs and have them float:left

Further- append does not do what you think it does. It's dom manipulation and not string manipulation- you can't use it to directly change HTML the way you're thinking.

Further reading

Try looking at .after(); function:

http://api.jquery.com/after

i think that you need to try with this selector

Asumming that your table haved an id called example try like this

$("#exmaple tr:last").append('<tr></tr>');
$('</tr><tr>').insertAfter('.row');

您想在tr元素上进行追加,而不要在td.row上进行追加

You need to not think in terms of constructing HTML markup. There's no way to splice a closing/opening </tr><tr> into the DOM (without some ugly .innerHTML hacks).

Instead, create a new row after the current row, and the relocate the cells into that new row.

var row_cells = $('td.row').slice(1);

row_cells.each( function( i, el ) {
    $('<tr>').insertAfter( row_cells.eq(i).parent() )
             .append( row_cells.eq(i) );
});

DEMO: http://jsfiddle.net/EDf5a/


Or maybe you wanted a new row for each cell:

var row_cells = $('td.row');
var row = row_cells.parent();

row_cells.each(function(i, el) {
    $('<tr>').insertBefore(row)
        .append(row_cells.eq(i));
});

DEMO: http://jsfiddle.net/EDf5a/1/

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