【发布时间】:2019-12-26 04:31:54
【问题描述】:
您好,我正在尝试从输入选项和文本字段中获取数据并插入到表格中。
我是用 javascript 和 jquery 完成的,但是在向表中插入数据后,执行 dataSend 函数后,我的 javascript 将停止工作。
$(document).ready(function() {
//variables
var status = $(".status");
var comment = $(".comments");
var questionsVal;
var statusVal = "test";
var commentsVal = "test2";
function dataSend() {
var inputText = jQuery('input[type="text"]');
var inputRadio = jQuery('input[type="radio"]');
var i = -1;
var i2 = -1;
while (i < inputText.length - 1) {
i++;
comment[i].innerHTML = inputText.eq(i).val();
}
console.log("test1");
while (i2 < inputRadio.length - 1) {
i2++;
status[i2].innerHTML = inputRadio.eq(i2).val();
}
console.log("test2");
}
jQuery("#dataSend").click(function() {
dataSend();
console.log("ok");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="dataExport">
<table>
<thead>
<tr>
<th>#</th>
<th>Questions</th>
<th>Status</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>First question</td>
<td class="status"></td>
<td class="comments"></td>
</tr>
<tr>
<th>2</th>
<td>Second question</td>
<td class="status"></td>
<td class="comments"></td>
</tr>
<tr>
<th>3</th>
<td>Third question</td>
<td class="status"></td>
<td class="comments"></td>
</tr>
</tbody>
</table>
</div>
<div id="questions">
<div>
<h4>First question</h4>
<form>
<p>Choose 1 option</p>
<input type="radio" name="question1" value="ok" checked="checked"> Ok<br>
<input type="radio" name="question1" value="error"> Error<br><br>
<p>Comment</p>
<input type="text" name="comment1" value="Comment1">
</form>
</div>
<div>
<h4>Second question</h4>
<form>
<p>Choose 1 option</p>
<input type="radio" name="question2" value="ok"> Ok<br>
<input type="radio" name="question2" value="error" checked="checked"> Error<br><br>
<p>Comment</p>
<input type="text" name="comment2" value="Comment2">
</form>
</div>
<div>
<h4>Third question</h4>
<form>
<p>Choose 1 option</p>
<input type="radio" name="question3" value="ok" checked="checked"> Ok<br>
<input type="radio" name="question3" value="error"> Error<br><br>
<p>Comment</p>
<input type="text" name="comment3" value="Comment3">
</form>
</div>
<div id="buttons">
<button id="dataSend">Send data to table</button>
</div>
</div>
在我的代码中,你可以看到控制台 test1、test2,ok。
我无法得到 test2 和好的。
你可以在 codepen 中看到这个:https://codepen.io/soorta/pen/gOYLpYq?editors=1111
感谢您的帮助。
【问题讨论】:
-
您正在访问
status[i2],其中i2==3。您已超出数组的范围 -
你确定@LeeTaylor?
i2被初始化为 -1? -
@radarbob - 非常确定。我逐步浏览了代码。 i2 设置为 -1 但随后 i2++ 发生...
标签: javascript jquery html