foreach ($question['a'] as $a) {
?>
<div class="radio">
<input type="radio" name="answerswer" id="answerswer" value="<?php echo $count ?>"><label id="answerswerLabel" for="answerswer"><?php echo $a['name'] ?> </label>
<?php $count = $count + 1; ?>
</div>
<?php } ?>
$.ajax({
///url,data etc
success: function (data) {
$('#index').val(data.index);
$answers = data.question.a;
$answers.forEach(function(item) {
console.log(item['name']);
$('#answerLabel').html(item['name']);
})
}
});
我正在尝试更新foreach循环中的标签文本,但只有第一个值更新并且单选按钮也消失了。控制台日志按原样显示 4 个项目。
问题var_dump['a']:
array(4) {
[0]=>
array(4) {
["id"]=>
string(2) "12"
["questionId"]=>
string(1) "4"
["name"]=>
string(7) "correct"
["correct"]=>
string(1) "0"
}
[1]=>
array(4) {
["id"]=>
string(2) "10"
["questionId"]=>
string(1) "4"
["name"]=>
string(7) "correct"
["correct"]=>
string(1) "0"
}
[2]=>
array(4) {
["id"]=>
string(1) "9"
["questionId"]=>
string(1) "4"
["name"]=>
string(7) "correct"
["correct"]=>
string(1) "1"
}
[3]=>
array(4) {
["id"]=>
string(2) "11"
["questionId"]=>
string(1) "4"
["name"]=>
string(7) "correct"
["correct"]=>
string(1) "0"
}
}
根据 jameshwart lopez 的回答,我将$count附加到标签的 id 上,然后在 ajax 中计数 =1,并在 foreachloop 中添加 1。这解决了问题。
Id 用于 only.in 您的情况的唯一元素answerLabel
您可以尝试连接名称或向该 id 添加一些内容,使其成为唯一元素。
样本
$count =0;
foreach ($question['a'] as $a) {
?>
<div class="radio">
<input type="radio" name="answerswer" id="answerswer<?php echo $count;?>" value="<?php echo $count ?>"><label id="answerswerLabel<?php echo $count;?>" for="answerswer"><?php echo $a['name'] ?> </label>
<?php $count = $count + 1; ?>
</div>
<?php } ?>
$.ajax({
///url,data etc
success: function (data) {
$('#index').val(data.index);
$answers = data.question.a;
count =0;
$answers.forEach(function(item) {
console.log(item['name']);
$('#answerLabel'+count).html(item['name']);
count = count+1;
})
}
});
希望有帮助。