jQuery UI 按钮栏(Button Group)是一种将多个按钮组合在一起的 UI 组件,可以通过配置使其像单选按钮(Radio Button)一样工作,即在同一组中只能选择一个选项。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#radio" ).buttonset();
} );
</script>
</head>
<body>
<div id="radio">
<input type="radio" id="radio1" name="radio"><label for="radio1">选项1</label>
<input type="radio" id="radio2" name="radio"><label for="radio2">选项2</label>
<input type="radio" id="radio3" name="radio"><label for="radio3">选项3</label>
</div>
</body>
</html>
$(function() {
$("#buttons").buttonset();
});
<div id="buttons">
<input type="radio" id="button1" name="button" checked="checked">
<label for="button1">选项A</label>
<input type="radio" id="button2" name="button">
<label for="button2">选项B</label>
<input type="radio" id="button3" name="button">
<label for="button3">选项C</label>
</div>
原因:没有为所有单选按钮设置相同的 name
属性
解决:确保组内所有 <input type="radio">
元素具有相同的 name
属性
原因:可能缺少 jQuery UI CSS 文件 解决:确保正确引入了 jQuery UI 的 CSS 文件
原因:可能在初始化按钮组后动态添加了新按钮
解决:在添加新按钮后重新调用 .buttonset()
方法
$("#radio").buttonset("refresh");
var selectedValue = $("input[name='radio']:checked").val();
$("#radio2").prop("checked", true).button("refresh");
$("input[name='radio']").on("change", function() {
console.log("选中了: " + $(this).attr("id"));
});
通过以上方法,可以轻松实现 jQuery UI 按钮栏的单选按钮功能,并根据需要进行定制和扩展。
没有搜到相关的文章