I have situation where I have structure like:
<table>
<tr class="chk"></tr>
<tr>one<tr>
<tr>two<tr>
<tr>three<tr>
<tr>four<tr>
<tr class="chk"></tr>
</table>
<table>
<tr class="chk"></tr>
<tr>one<tr>
<tr>two<tr>
<tr>three<tr>
<tr>four<tr>
<tr class="chk"></tr>
</table>
Now what I want to do is to do something when tr chk is clicked. What I am doing right now is:
$(".chk:even").click(function(){
//do something
});
$(".chk:odd").click(function(){
//do something
});开发者_开发知识库
Note: The above is working as I want.
I was wondering how I can determine if row is even or odd in a single function like:
$(".chk").click(function(){
if(row is even){
//do something
}
else{
//do something
}
});
Or is what I already have better or fine than the new version I am seeking?
Let me know if question is not clear.
Try this:
$(".chk").click(function(){
var bIsEven = ($(this).index(".chk") % 2 == 0)?true:false;
if(bIsEven){
//do something
} else{
//do something
}
});
Working example: http://jsfiddle.net/3h23G/6/
The version you have is more "optimal" in that it will run the query once at page setup and attach the click handlers. After that each time the elements are clicked it will just execute a function without any conditionals. The way you are seeking will cause a query to run on every click. Whether or not that matters depends on your application.
You're original way will iterate through the rows twice, true, but that will be done at page load time. The way you seek would iterate only once at startup, but then inside the click handler you need to wrap the 'this' object in a jQuery object every time it runs to determine if it's ":even".
Allocating a new object is generally more expensive than iterating over a reasonably sized set.
$(".chk").click(function(){
var evens = $(".chk:even");
if (jQuery.contains( evens, row )){
//do something
} else{
//do something
}
});
var chks = $("tr.chk");
for(var i=0;i<chks.length;i++) {
// even
if(i % 2 == 0) {
}
else { // odd
}
}
Try this (demo):
$('table tr').click(function(){
var row = $(this),
color = (row.index() % 2) ? 'red' : 'blue';
row.css('background', color);
});
it's odd the the .is(':even')
and .is(':odd')
isn't working...
Well if nothing else works, you can use .index(); to get the 0-based index and then use % 2.
精彩评论