简体   繁体   中英

Pass variable and DOM element to jquery each

I've been struggling with this for a while, and have tried many searches, but haven't found the right solution, nor words for the issue I have. I wish to traverse the <tr> 's in <table id="Listeners"> with jQuery, and set the rows to either Even or Odd class.

The is yet saved in a variable and passed to the function, as follows:

<table id="Listeners">
 <tr><td>1</td></tr>
 <tr><td>2</td></tr>
</table>

And my jQuery:

var Element = $("#Listeners");
$(Element+" tr").each(function(index) {
 if (index%2 == 0) {
  $(this).addClass("Even");
 }
});

But that doesn't work, any thoughts on how to solve this?

You can use find() method and :even selector:

Selects even elements, zero-indexed.

var $element = $("#Listeners");
$element.find("tr:even").addClass("Even");
// or $element.find("tr").filter(':even').addClass("Even")

There are many ways to do this. This should work:

$('#Listeners tr:nth-child(even)').addClass("Even");

See: http://api.jquery.com/nth-child-selector/

Even this:

$('#Listeners tr:even').addClass("Even");

See it working here: http://jsfiddle.net/zm2nN/

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