【问题标题】:obtain position of nth-child to variable获取第 n 个孩子的位置到变量
【发布时间】:2025-12-15 01:50:01
【问题描述】:

我有一张桌子:


<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);
});

请注意,每一个都有些不同 - 在过去的很多天里,我尝试了许多其他变体。我还查看了我找到的所有示例,但似乎没有任何效果。帮助。谢谢。瑞克

【问题讨论】:

  • 请详细说明您想要实现的目标,因为您的代码根本没有意义。

标签: jquery variables jquery-selectors


【解决方案1】:

为了获得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/

【讨论】:

  • 或者,您也可以使用.map$("#my_table img").map(function(){return this.alt;}).get().join(", ")
【解决方案2】:

这个怎么样?

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() method评估点击图片的索引。

【讨论】:

    【解决方案3】:

    在您遍历集合时提供索引:

    $("#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)); 
    });
    

    【讨论】: