我正在使用jquery函数.prop()从ajax返回的一组无线电输入中检查特定的无线电输入。它先检查了所需的输入,然后再次取消选中。我创建了一个按钮,当单击该按钮时,它将调用ajax函数,而ajax返回放置在<ul>
标记中的单选输入组列表。 <ul>
标签的HTML代码。
<ul id= "list_option">
// here ajax response will come
</ul>
按钮代码:
<button class="btn btn-primary get_option" type="button" data-selected_option="2">click</button>
按钮调用的功能:
$(document).on('click', '.get_option', function(){
var checked_answer_id = $(this).attr('data-selected_option');
get_opt();
$('#option_id_'+checked_answer_id).prop('checked',true);
});
注意:我使用attr()函数而不是data('selected_option'),因为attr返回的值由于某种原因data函数没有返回。Ajax的功能:
function get_opt()
{
$.ajax({
url:"ajax_action.php",
method:"POST",
dataType: 'JSON',
data:{action:'get_option'},
success:function(response)
{ $('#list_option').html(response);}
})
}
HTML代码从ajax_action.php页面返回:
$output='
<li class="list-group-item border rounded border-success answer-item-list">
<div class="form-check">
<input class="form-check-input answer_option" type="radio" id="option_id_1" name="opt_grp" value="1">
<label class="form-check-label" for="option_id_1" > OPTION 1</label>
</div>
</li>
<li class="list-group-item border rounded border-success answer-item-list">
<div class="form-check">
<input class="form-check-input answer_option" type="radio" id="option_id_2" name="opt_grp" value="2">
<label class="form-check-label" for="option_id_2"> OPTION 2</label>
</div>
</li>
';
echo $output;
以上所有代码都工作正常,除了prop函数检查了所需的无线电输入(在这种情况下暂时是选项2,然后未经检查)。我不知道我在做什么错。
这是这些天好孩子的做法;)
将async
/ await
用于调用$.ajax
的函数,等待ajax调用完成,然后将结果返回给调用函数。
我们使用.then()
,因此我们也不必将准备好文档的匿名函数异步并等待get_opt()
。通过使用then,它将始终等待get_opt完成。
然后您可以在result
方法内部对.then()
进行操作,并希望将prop
设置为在单选按钮上选中,而以后不会被覆盖。
$(document).on('click', '.get_option', function(){
var checked_answer_id = $(this).attr('data-selected_option');
get_opt().then((result) => {
$('#option_id_'+checked_answer_id).prop('checked',true);
$('#list_option').html(result);
});
});
async function get_opt() {
let result;
try {
result = await $.ajax({
url:"ajax_action.php",
method:"POST",
dataType: 'JSON',
data:{action:'get_option'},
});
return result;
} catch (error) {
console.log(error);
}
}