尝试在两次迭代中警告同一选择器的值,在第一次迭代中得到正确的值,而在第二次迭代中获得不正确的值.为什么?
Trying to alert value of same selector in two iterations, getting correct value in 1st iteration and incorrect one in second. Why?
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中,迭代器变量似乎永远不会在弹出的警报中前进。
相关文章:
- 如果30秒未单击,请应用CSS一次,将其删除,然后重新迭代
- 循环中的切换脚本只适用于第一次迭代
- 尝试在两次迭代中警告同一选择器的值,在第一次迭代中得到正确的值,而在第二次迭代中获得不正确的值.为什么?
- 我的Javascript for循环在1次迭代后停止
- 执行在外循环的第一次迭代后停止
- 角度达到 10 次 $digest() 迭代
- Javascript音频分层eventListener HTML5在多次迭代中失败
- 此代码在第一次迭代时给出 0 作为高度和宽度,第二次给出正确的尺寸
- for循环只迭代一次
- 如何在ajax完成后执行第二次循环迭代
- JavaScript uncatch TypeError:无法在第二次迭代时调用未定义的方法“拼接”
- angularjs.for每次第二次迭代都无法设置对象属性
- 当我将src附加到图像时,每N秒迭代一次
- 当试图从元素中删除类时,For循环只迭代一次
- 每个函数在XML中迭代两次
- 对对象数组只迭代一次
- Javascript - for循环只迭代一次
- 迭代一次的行值并添加
- Regex.prototype.exec在搜索的第二次迭代中返回null
- JavaScript在同一循环中每x次迭代一次循环