【发布时间】:2020-08-26 08:33:38
【问题描述】:
我正在使用 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);}
})
}
从 ajax_action.php 页面返回的 HTML 代码:
$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,然后它被取消选中。我不知道我做错了什么。
【问题讨论】:
-
我似乎无法重现您的问题:jsfiddle.net/teddyrised/a09j67d2。当点击事件处理程序被触发时,您确定从 AJAX 返回的 HTML 代码被解析并插入到 DOM 中吗?
-
嘿,记住,你的 get_opt() 函数会触发一个异步 http-request。您的
jquery().prop()在此请求完成之前 被调用。在.html()调用之后,您应该将其放入您的 succesd 函数中。 -
$('#list_option').html(response);所以你用来自ajax_action的内容覆盖.prop("checked", true)。在每一行添加一个console.log("1")(2,3...),这样您就可以看到它们的执行顺序。看起来您希望$('#list_option').html(response);在.prop('checked',true);之前运行,但它不会。 -
非常感谢cars10m 和freedomn-m。就像你说的那样。我认为该语句将按顺序执行。所以 prop() 语句将在 get_opt() 完成时执行。但现在正如你所建议的,我将 prop 语句放在成功函数中并且它工作正常。再次感谢。
标签: jquery ajax radiobuttonlist prop