1

私はテーブルを持っています:


<table width="160" align="center" id="my_table">
    <tbody>
       <tr>
          <td><img src="Color1.png" width="160" height="40" alt="1"></td>
       </tr>
       <tr>
          <td><img src="Color2.png" width="160" height="40" alt="2"></td>
       </tr>
       <tr>
          <td><img src="Color3.png" width="160" height="40" alt="3"></td>
       </tr>
   </tbody>
</table>

ユーザーが色のブロックを上下に移動できるようにします。さらに多くの色があります。プロセスの最後に、各 alt がどの位置 (どの子位置) にあるかを知り、それを jQuery を使用して個別の変数に保存したいと考えています。私はもう試した:

$('#my_table').on('click', 'img', function() {
    var color_rated_1 = $("#my_table.tr:nth-child(1)");
    alert("color_rated_1 is " + color_rated_1);
});
$('#my_table').on('click', 'img', function() {
    var color_rated_2 = $(".tr:nth-child(2)");
    alert("color_rated_2 is " + color_rated_2);
});
$('#my_table').on('click', 'img', function() {
    var color_rated_3 = $("#my_table tr:nth-child(3)");
    alert("color_rated_3 is " + color_rated_3);
});

これらはそれぞれ少しずつ異なることに注意してください - そして、私は過去何日もの間、他の多くのバリエーションを試してきました. 私が見つけたすべての例も見ましたが、何も機能していないようです。ヘルプ。ありがとう。リック

4

3 に答える 3

2

コレクションを反復処理すると、インデックスが提供されます。

$("#my_table img").each(function(index, image){
    alert(image.alt + " is at position " + index);
});​

.index()コレクション内の場所を取得するために使用することもできます。

var $table = $("#my_table");
$table.on("click", "img", function(){
    alert($table.find("img").index(this)); 
});
于 2012-11-18T07:15:37.353 に答える
0

表示される順序で値の配列を取得するにaltは、次のようにします。

   var order = $.makeArray($("#my_table img").map(function() {
       return $(this).attr("alt");
   }));

   alert("The order is " + order.join(", "));

http://jsfiddle.net/BUmr2/1/

または、alt をキーとするオブジェクトを作成するように命令することもできます。

   var indexes = {};

   $("#my_table img").each(function(i) {
       indexes[$(this).attr("alt")] = i;
   });

   alert("Index 1 is " + indexes["1"]);
   alert("Index 2 is " + indexes["2"]);
   alert("Index 3 is " + indexes["3"]);

http://jsfiddle.net/ec9HY/

于 2012-11-18T07:40:19.107 に答える
0

これはどう?

var $table = $('#my_table').on('click', 'img', function() {
   var index = $table.find("img").index(this);

   alert( $(this).attr("src") + " is " + index);
});

http://jsfiddle.net/YAAaE/

画像がクリックされると、テーブル内のすべての画像が検索され、.index()メソッドを使用してクリックされた画像のインデックスが評価されます。

于 2012-11-18T07:22:12.143 に答える