如何通过编程检查/取消检查jquery-ui checkboxradio

r9f1avp5  于 2023-04-11  发布在  jQuery
关注(0)|答案(2)|浏览(112)

我正在尝试通过编程方式(即不使用鼠标)选中/取消选中jquery-uicheckboxradio小部件。我已经尝试了各种方法,但没有乐趣。要重现这个问题,请选择一个只有jqueryjquery-ui脚本标记的空白html页面,然后动态创建小部件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blank</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
</body>
</html>

页面加载后,我点击F12以打开dev-tools,并输入以下命令以获得最小的jquery-ui复选框:

$container = $("<div>")
$container.append($("<label for='chkbox'>"))
$container.append($("<input type='checkbox' id='chkbox'>"))
$container.appendTo('body')
$('#chkbox').checkboxradio()

默认情况下,该复选框未选中。让我们尝试选中它:

$('#chkbox').attr('checked', true) // nope
$('#chkbox').checkboxradio('refresh') // nope
$('#chkbox').attr('checked', false)
$('#chkbox').prop('checked', true) // nope
$('#chkbox').prop('checked', false)
$('#chkbox').addClass('ui-checkboxradio-checked') // not this either
$('#chkbox').removeClass('ui-checkboxradio-checked')
$('#chkbox').checkboxradio('option', 'classes.ui-checkboxradio-checked', true) // does nothing
$('#chkbox').checkboxradio('option', 'ui-checkboxradio-checked', true) // does nothing
$('#chkbox').checkboxradio('option', 'classes.ui-checkboxradio.ui-checkboxradio-checked', true) // and again, nothing...

这真令人恼火。有人有办法解决这个看似简单的问题吗?

hmae6n7t

hmae6n7t1#

希望对你有所帮助谢谢。

$container = $("<div>")
$container.append($("<label for='chkbox'>"))
$container.append($("<input type='checkbox' id='chkbox' >"))
$container.appendTo("body")
 $("#chkbox").checkboxradio();
$("#chkbox").prop("checked",true).checkboxradio("refresh")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blank</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
</body>
</html>
flseospp

flseospp2#

您需要调用change函数,因为jquery ui将在更改时更改视觉效果,因此仅设置checked属性不会产生任何效果

$("#chkbox").attr("checked","checked").change();

相关问题