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

这个怎么样?

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