2016-03-30 8 views
2

テーブル行のtd要素の位置を調べるにはどうすればよいですか?私はこのコードが示唆しているのを見ましたが、各tdタグにonclickイベントが含まれていることでこれを行う方法がありますか?テーブル行のTD要素位置の検索

<table> 
    <tr> 
    <td onclick="myFunction(this)">Click to show cellIndex</td> 
    <td onclick="myFunction(this)">Click to show cellIndex</td> 
    <td onclick="myFunction(this)">Click to show cellIndex</td> 
    <td onclick="myFunction(this)">Click to show cellIndex</td> 
</tr> 
</table> 

<script> 
function myFunction(x) { 
    alert("Cell index is: " + x.cellIndex); 
} 
</script> 

グリッドがあり、グリッド内のどの画像がクリックされたかを確認しようとしています。バニラでクリックTD

+2

の可能性のある重複した[ジャバスクリプト:取得TD指数](http://stackoverflow.com/questions/ここ

$('td img').click(function(){ var index = $(this).parent().index(); }); 

はフィドルです6470877/javascript-getting-td-index) –

答えて

3

$('td img').on('click', function(e) { 
 
    var td = $(this).parent(); 
 
    var tr = td.parent(); 
 
    
 
    var children = tr.children().length; 
 
    
 
    var tdIndex = td.index() + 1; 
 
    var trIndex = tr.index(); 
 
    
 
    console.log((trIndex * children) + tdIndex); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td><img src="1.jpg" /></td> 
 
    <td><img src="2.jpg" /></td> 
 
    </tr> 
 
    <tr> 
 
    <td><img src="1.jpg" /></td> 
 
    <td><img src="2.jpg" /></td> 
 
    </tr> 
 
</table>

+0

大規模なグリッド、たとえば8 x 8を使用していた場合、 2番目の行の最初のイメージをクリックしましたか? –

+0

はい、あなたの要求に応じてスニペットを編集しました。 –

1

$('table tr td').click(function() { 
 

 
    console.log($(this).index()) //use index() to get the index of clicked td 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td>Click to show cellIndex|</td> 
 
    <td>Click to show cellIndex|</td> 
 
    <td>Click to show cellIndex|</td> 
 
    <td>Click to show cellIndex|</td> 
 
    </tr> 
 
</table>

をログに記録します。私はこれを試してみましたJavaScriptのように扱うことができます:

​​

onclickイベントをページの各TD要素にアタッチします。ここにはFiddle of it in actionがあり、jQueryではxの参照先を指定するだけです。

$('td').on('click', function(e){ 
    alert('this.cellIndex: ' + this.cellIndex + '\n$(this),index(): ' + $(this).index()); 
}); 

Documentation on event.target

2

のインデックスを取得するために.index()をtdのと使用するためにクリックを添付

$('td img').on('click', function(x){ 
    console.log("Cell index is: " + x.cellIndex); 
}); 

しかし、それだけでundefined

9

あなたは、オブジェクトのインデックス

https://api.jquery.com/index/

function myFunction(x) { 
    alert($(x).index()); 
} 

を取得するためにjqueryので$ .INDEX()関数を使用することができ、それがお役に立てば幸いです。

関連する問題