javascript / 如何在 nth-child of 2 类 中设置相同的值

javascript / how to set the same value in nth-child of 2 classes

https://codepen.io/jh-ko/pen/OBrMOO

 var table = [1, "red", 3, 
              4, "blue", 6];
  for (var i = 0; i < table.length; i += 3) {
 var x = table[i];
 var y = table[i+1];
 $(".Ali:nth-child(" + (x++) + ")").click(function() {
 $("div .me:nth-child(" + (x++) + ")").css("color", y);
});
}

--上面有例子(codepen)--

我有 2 个 class .Ali 和.me

首先,我希望两个 class 具有相同的 nth-child 值。 例如,当我点击阿里 class 的 nth-child(1) 时, 我想在我 class.nth-child(1) 中获得红色。

但是我在这段代码中得到了蓝色,...

当我直接用数字编码时,效果很好。

".Ali:nth-child(4)"
"div .me:nth-child(4)"

我的目标: 当我点击 A 组中的一个数字(例如 3)时, 我想在 B 组中使用相同号码的颜色..

首先,这是一个可行的解决方案:

var table = ["red", "yellow", "pink", "blue", "green", "gold"];

$(".Ali").click(function() {
   var i = $(this).index();
   $("div .me").eq(i).css("color", table[i]);
 });

您的问题是 "x" 变量在您第二次使用时采用了不同的值。

执行顺序是这样的:

  • 第一次迭代(针对):
    1. 我是 0
    2. x 是 table[0] = 1
    3. 您将一个动作分配给“.Ali:nth-child(1)
    4. x 是 x++ = 2
    5. y 是 table[1] = "red"
  • 第二次迭代(对于)
    1. 我是 3
    2. x 是 table[3] = 4
    3. 您将一个动作分配给“.Ali:nth-child(4)
    4. x 是 x++ = 5
    5. y 是 table[5] = "blue"
  • 第一次点击
    1. x 为 5
    2. 你将颜色更改为 $("div .me:nth-child(5)")
    3. 颜色是"blue"
  • 第二次点击
    1. x是6,你把颜色改成$("div .me:nth-child(6)")
    2. 颜色是"blue"
  • 等等...

如果您使用全局变量,例如您的 x 和 y,则每次更改都是全局的。

您能否查询被点击元素的索引并将其与您要从中检索数据的元素的索引进行比较?

使用 .index() 您可以找到被点击的元素在其顺序中的位置。使用 .eq()/:eq(),您可以通过元素在组中的索引来定位元素。

$('.me').click(function(){
  let i = $(this).index();
  i = i-1;
  console.log( $(`.ali:eq(${i})`).css('background-color') );
});
.ali, .me{
  height: 20px;
  width: 20px;
  display: inline-block;
  float: left;
  margin: 5px;
}

.me{ background-color: black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="me"></div>
<div class="me"></div>
<div class="me"></div>
<div class="me"></div>
<div class="me"></div>
<div class="me"></div>
<div class="me"></div>
<div class="me"></div>
<div class="me"></div>

<div style="clear: both; width: 100%; "></div>

<div class="ali" style="background-color: red;"></div>
<div class="ali" style="background-color: rebeccapurple;"></div>
<div class="ali" style="background-color: blue;"></div>
<div class="ali" style="background-color: green;"></div>
<div class="ali" style="background-color: yellow;"></div>
<div class="ali" style="background-color: orange;"></div>
<div class="ali" style="background-color: red;"></div>
<div class="ali" style="background-color: rebeccapurple;"></div>
<div class="ali" style="background-color: blue;"></div>