开发者

Dynamic item insertion messing up the zebra striping

I have a simple list of products where zebra striping is achieved using the cycle method.

Here is the product partial:

<tr class="product <%= cycle 'odd', 'even' %>">
  <td><%= product.name %></td>
  <td><%= product.price %></td>
  <td><%= product.percentage %></td>
  <td><%= link_to "Show", product %></td>
  <td><%= link_to "Edit", edit_product_path(product), :remote => true %></td>
  <td><%= link_to "Destroy", product, :confirm => 'Are you sure?', :method => :delete, :remote => true %></td>
</tr>

However, when I dynamically insert another product, the cycle method logically picks the first class (in this case the "开发者_开发技巧odd" class) thus breaking the striping until the next reload. Although dynamically reloading the entire product would work; this method seems somewhat dirty and would likely mess with the pagination. Since I'm still relatively new to JavaScript and Prototype I'm unable to come up with this on my own so I have to ask: Is there a way to get the class of the previous product ("odd" or "even") and add class to the newly inserted product accordingly?

My current UJS used to insert the partial:

Modalbox.hide();

function insertProduct() {
   $('products').insert( { top: "<%= escape_javascript(render @product) %>" } );
   $$('.product').first().highlight(); 
}

insertProduct.delay(0.8);

Any help would be much appreciated.

Thanks in advance.


After you insert elements, you need to remove all class odd and even:

$('tr.product').removeClass('odd even');

Then you need to add classes again:

$('tr.product:even').addClass('even');
$('tr.product:odd').addClass('odd');

so the code will be like this:

[...]
$$('.product').first().highlight(); 
$('tr.product').removeClass('odd even');
$('tr.product:even').addClass('even');
$('tr.product:odd').addClass('odd');
}


Ionut Staicu is essentially right but has forgotten it's Prototype. Final answer should be;

$$('.product').invoke('removeClassName', 'odd')
              .invoke('removeClassName', 'even')
              .first().highlight(); 
$$('.product:even').invoke('addClassName', 'even');
$$('.product:odd').invoke('addClassName', 'odd');


In jQuery, I do it like this:

$('#product-<%= @product.id %> ~ .product').each(function(index) {
  $(this).toggleClass('odd');
  $(this).toggleClass('even');
});

The selector says: find product with id "product-XX", then for every following element that has a class product, toggle class odd and even (remove it if it's present, and add it if it's not).


Were I doing this and if I could rely on each row being a fixed height I would probably use a striped background image instead. That doesn't allow for differing foreground colours or any CSS property than a background. Still, it would be very reliable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜