Get the index of the clicked row index
I am new to mootools but have good knowledge on jQuery,
I am trying to get the index of the on click. Here is my HTML code..<table>
<tr><td>One</td><td>Two</td><td>Three</td></tr>
<tr><td>Four</td><td>Five</td><开发者_如何学运维;td>Six</td></tr>
<tr><td>Seven</td><td>Eight</td><td>Nine</td></tr>
<tr><td>Ten</td><td>Eleven</td><td>Twelve</td></tr>
</table>
And below is my Mootools code,
$$('TABLE TBODY TR TD').addEvent('click',function(el)
{
alert($(this).index());
});
It seems the code is wrong, Please someone let me know nay functions to get the properties of elements.
First of all, $(this)
inside the callback is jQuery stuff. In mootools, to get the index of the current row you could retrieve the collection of rows, iterate them, and attach click event to all td children:
$$('table tr').each(function(row, index){ //row is the current tr, index is fairly self-explanatory :P
//for each row, get its td children, attach the click event, and alert the 'index' (the number of the row)
row.getElements('td').addEvent('click',function(){
alert(index);
});
//or, if you just want to know the index of the row without doing something with each td, just attach the click event to the row
});
demo: http://jsfiddle.net/steweb/UN5jd/
EDIT : to get td indexes too, you could do something like this:
$$('table tr').each(function(row, index){
row.getElements('td').each(function(column, i){
column.addEvent('click',function(){
alert("Row: " + index + " --- " + "Column: "+i);
});
});
});
demo2: http://jsfiddle.net/steweb/UN5jd/2/
Here is a cleaner way:
$$('table tr td').addEvent('click', function(e){
var index = this.getParent('tr').getElements('td').indexOf(this);
console.log(index);
});
Working example: http://jsfiddle.net/kt9aN/
精彩评论