获取单击的行索引的索引

时间:2011-07-31 18:08:28

标签: mootools

我是mootools的新手,但对jQuery有很好的了解,
我试图得到点击的索引。
这是我的HTML代码..

<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>

以下是我的Mootools代码,

 $$('TABLE TBODY TR TD').addEvent('click',function(el)
                             {
                                 alert($(this).index());
                             });

似乎代码错了,请有人让我知道nay函数来获取元素的属性。

2 个答案:

答案 0 :(得分:2)

首先,回调中的$(this)是jQuery的东西。在mootools中,要获取当前行的索引,您可以检索the collection of rowsiterate them,并将click事件附加到所有td子项:

$$('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        

});

演示:http://jsfiddle.net/steweb/UN5jd/

编辑:要获得td索引,你可以这样做:

$$('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/

答案 1 :(得分:0)

这是一种更清洁的方式:

$$('table tr td').addEvent('click', function(e){
    var index = this.getParent('tr').getElements('td').indexOf(this);
    console.log(index);
});

工作示例:http://jsfiddle.net/kt9aN/