尝试在两次迭代中警告同一选择器的值,在第一次迭代中得到正确的值,而在第二次迭代中获得不正确的值.为什么?

Trying to alert value of same selector in two iterations, getting correct value in 1st iteration and incorrect one in second. Why?

本文关键字:迭代 第二次 第一次 为什么 不正确 选择器 两次 警告      更新时间:2023-09-26

JSFiddle

在以下SSCCE中,有两个.inner-table元素。我已经使用JQuery each()对它们进行了迭代。然后在每个.inner-table中,我使用val()函数迭代每个<tr>,以找出并警告<input>.color-name元素的值。

问题是,在第一次迭代中,<input>.color-name的警报显示值显示了我在文本字段中输入的正确值,但在第二次迭代中(即第二次inner-table),无论我在文本域中写入什么,警报似乎都显示了一个空字符串。

问题是为什么?我做错了什么?

$(document).on("click", "#button", function(event) {
  //event.preventDefault();
  alert('Button clicked.'); //check
  var colorName;
  var dataJSON = {};
  $(".inner-table").each(function() {
    var dataUnit = [];
    dataJSON.dataUnit = dataUnit;
    var iterationCount = 1;
    
    $(this).find("tbody tr").each(function() {
      alert("Iteration " + iterationCount); //check
      //alert($(this).html());//check
      if ($(this).find("td .color-name").length) {
        colorName = $(this).find("td .color-name").val();
        alert(colorName); //check
      }
      iterationCount++;
    });
    var color = {
      "colorName": colorName
    };
    dataJSON.dataUnit.push(color);
  });
  console.log("dataJSON > " + JSON.stringify(dataJSON)); //check
});
.outer-table tr {
  margin: 30px;
}
.inner-table {
  border: 2px solid yellow;
  background-color: wheat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">
  Click
</button>
<table class="outer-table">
  <tbody>
    <tr>
      <td colspan="3">
        <table class="inner-table">
          <tbody>
            <tr>
              <td>
                <p class="input-label">Name of Color</p>
                <input class="input-field color-name" type="text" />
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
    <!-- ------------------------------------------------- -->
    <!-- ------------------------------------------------- -->
    <!-- ------------------------------------------------- -->
    <tr>
      <td colspan="3">
        <table class="inner-table">
          <tbody>
            <tr>
              <td>
                <p class="input-label">Name of Color</p>
                <input class="input-field colorName" type="text" />
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
  </tbody>
</table>

您在第二个td中使用了错误的类名。您使用的是"colorName",应该是"colorName"

您应该在此处阅读有关each API的更多信息:http://api.jquery.com/jQuery.each/.您应该更改回调函数以接受包括迭代变量在内的参数,而不是声明自己的参数。我认为这是你们解决方案的开始。在jsfiddle中,迭代器变量似乎永远不会在弹出的警报中前进。