foreach ($question['a'] as $a) {
?>
<div class="radio">
<input type="radio" name="answer" id="answer" value="<?php echo $count ?>"><label id="answerLabel" for="answer"><?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中使count = 1并在foreachloop中添加1。 这解决了这个问题。
答案 0 :(得分:-1)
Id仅适用于唯一元素。在您的情况answerLabel
中,您可以尝试连接名称或向该ID添加一些内容,使其成为唯一元素。
样品
$count =0;
foreach ($question['a'] as $a) {
?>
<div class="radio">
<input type="radio" name="answer" id="answer<?php echo $count;?>" value="<?php echo $count ?>"><label id="answerLabel<?php echo $count;?>" for="answer"><?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;
})
}
});
希望有所帮助。