如何在勾选复选框时禁用jQuery Dialog中的指定按钮?
问题描述
我希望勾选「Update the counter」复选框时,禁用jQuery Dialog中的一个按钮,但当前代码似乎没实现这个效果,请问现有代码能达成需求吗?
当前JS代码:
let additionalValue = "ABC12345"; console.log("Login next suggested value " + additionalValue + ""); let buttons = {}; // 使用括号表示法设置对象的动态属性键 buttons["Login next suggested value " + additionalValue] = function() { $(this).dialog("close"); }; buttons["Login case number of your choice"] = function() { $(this).dialog("close"); }; buttons["Cancel button"] = function() { $(this).dialog("close"); }; $("#dialog-confirm").dialog({ resizable: false, height: "auto", width: 400, modal: true, buttons: buttons });
当前HTML代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <title>jQuery UI Dialog - Modal confirmation</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <div id="dialog-confirm" title="Select your choice!?"> <p><span>The next sequential value for the Case number is 1001 .\n\nClick Yes to use the next sequential value or Cancel to proceed with yours!</span></p> <p><input type="checkbox" id="update_counter_checkbox" name="update_counter_checkbox" />Update the counter</p> </div>
回答
现有代码无法实现你的需求,因为缺少复选框事件监听逻辑和按钮状态切换的处理代码。要达成目标,需要补充以下核心逻辑:
- 监听复选框的
change事件,实时判断勾选状态 - 定位到目标Dialog按钮,调用jQuery UI的标准方法切换禁用/启用状态
假设你要禁用的是动态生成的「Login next suggested value ABC12345」按钮,修改后的完整代码如下:
let additionalValue = "ABC12345"; // 提前存储目标按钮的文本,方便后续匹配 let targetButtonText = "Login next suggested value " + additionalValue; console.log(targetButtonText); let buttons = {}; buttons[targetButtonText] = function() { $(this).dialog("close"); }; buttons["Login case number of your choice"] = function() { $(this).dialog("close"); }; buttons["Cancel button"] = function() { $(this).dialog("close"); }; // 初始化Dialog并绑定事件 $("#dialog-confirm").dialog({ resizable: false, height: "auto", width: 400, modal: true, buttons: buttons, // Dialog渲染完成后再绑定复选框事件,确保DOM元素已存在 open: function() { $("#update_counter_checkbox").on("change", function() { // 通过按钮文本匹配定位目标按钮 let targetButton = $(this) .closest(".ui-dialog") .find(".ui-dialog-buttonpane button") .filter(function() { return $(this).text() === targetButtonText; }); // 根据勾选状态切换按钮状态 if ($(this).is(":checked")) { targetButton.button("disable"); } else { targetButton.button("enable"); } }); } });
关键细节说明:
- 利用Dialog的
open回调确保组件渲染完成后再绑定事件,避免DOM元素未加载导致的匹配失败 - 通过按钮文本匹配动态生成的按钮(因为这类按钮没有固定ID)
- 使用jQuery UI的
button("disable")/button("enable")方法切换状态,这是操作jQuery UI按钮组件的标准方式
内容的提问来源于stack exchange,提问作者Tan
相关产品推荐
相关产品推荐

