Kendo Grid金额列最值设置失效:无法获取金额列ID求助
解决Kendo Grid编辑时获取Amount列输入框的问题
嘿,我明白你的困扰了!你直接用$("#amount")去查找输入框是行不通的,因为Kendo Grid在编辑模式下,每个行的输入框ID都会被自动加上前缀(比如网格ID、行的UID之类的),不是固定的amount,所以你根本找不到这个元素。
正确的获取方式
在Grid的edit事件里,我们可以通过e.container这个参数来定位当前编辑行内的Amount输入框——e.container就是当前正在编辑的单元格/行的容器,用它来查找元素就不会错啦!
另外还要注意:每次进入编辑模式都会触发edit事件,直接绑定click事件会导致重复绑定,多次触发逻辑,所以最好用事件委托或者确保事件只绑定一次。
修改后的完整代码
var grid = $('#grid').kendoGrid({ dataSource: dataSource, editable: true, //toolbar: [{ name: "create", text: "Add" }], columns: [ { field: "name", title: "name" }, { field: "status", title: "Status", template: data => data.status == "amt" ? "Amount" : "Percentage", editor: ` <input name='status' type='radio' data-bind='checked:status' id='perc' value='perc'> <label for='perc'>Percentage</label><br> <input name='status' type='radio' data-bind='checked:status' id='amt' value='amt'> <label for='amt'>Amount</label> ` }, { field: "amount", title: "Amount" }, { command: ["destroy"], title: " " } ], edit: function(e){ // 获取当前编辑行的amount输入框 const amountInput = e.container.find("[name='amount']"); // 用事件委托绑定单选框的点击事件,避免重复绑定 e.container.on("click", "#perc, #amt", function() { if ($("#perc").is(":checked")) { // 设置最大值最小值,并修正当前值 amountInput.attr({"max": 100, "min": 0 }); if (parseFloat(amountInput.val()) > 100) { amountInput.val(100); } } else { // 移除限制 amountInput.removeAttr("max min"); } }); // 绑定amount输入框的change事件 amountInput.on("change", function() { if ($("#perc").is(":checked")) { const currentVal = parseFloat($(this).val()); if (currentVal > 100) { $(this).val(100); } else if (currentVal < 0) { $(this).val(0); } } }); } });
关键改动说明
- 精准定位输入框:用
e.container.find("[name='amount']")代替$("#amount"),确保找到的是当前编辑行的Amount输入框。 - 优化事件绑定:使用
e.container.on()来绑定事件,这样事件只会绑定在当前编辑行的元素上,不会重复触发。 - 完善值的校验:不仅设置了
max/min属性,还在change事件里直接校验并修正值,避免用户输入超出范围的内容。 - 修正label的for属性:原来的label没有绑定对应的radio ID,现在加上了
for='perc'和for='amt',提升可访问性。
这样你的功能就能正常运行啦!
内容的提问来源于stack exchange,提问作者dontbannedmeagain
相关产品推荐
相关产品推荐

