You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编辑状态下如何禁用Knockout.js中Confirm按钮的点击事件?

Disable Click Event in Edit Mode (Knockout.js)

Alright, let's get this sorted. You want to stop the Confirm link from triggering the save function when you're in edit mode, and you've already added an observable to your Knockout view model. Here's how to tie everything together:

1. Update Your HTML Binding

You need to tweak the data-bind on your anchor tag to conditionally block the click. There are two straightforward ways to do this:

Option 1: Use enable (with visual feedback)

Anchor tags don't natively support the disabled attribute, but Knockout's enable binding will still prevent the click event from firing when the condition fails. We can add a CSS class to make it look disabled too:

<tr>
  <td>
    <a href="#" 
       data-bind="{
         click: $parent.save,
         enable: !confirmedRecord(),
         css: { 'disabled-link': confirmedRecord() }
       }">Confirm</a>
  </td>
</tr>

Add this quick CSS to style the disabled link so users can tell it's inactive:

.disabled-link {
  color: #ccc;
  cursor: not-allowed;
  text-decoration: none;
}

The enable: !confirmedRecord() part means the click will only work when confirmedRecord() is false (i.e., not in edit mode).

Option 2: Conditionally Run the Save Function

If you'd rather skip the enable binding, you can wrap the save call in a check right in the click handler:

<tr>
  <td>
    <a href="#" 
       data-bind="click: function() { if (!confirmedRecord()) $parent.save(); }">Confirm</a>
  </td>
</tr>

This way, the save function only runs when you're not in edit mode.

2. Double-Check Your Observable Setup

From your code snippet, you're setting vm.confirmedRecord(false) in the save function—just make sure you initialized this as a proper Knockout observable in your view model first:

// Initialize your view model with the observable
var vm = {
  selectedItem: ko.observable(),
  confirmedRecord: ko.observable(true) // Set this to true if you start in edit mode by default
  // ... other view model properties
};

// Your existing save function
vm.save = function () {
  var item = vm.selectedItem();
  vm.confirmedRecord(false); // Switch out of edit mode after saving
  // ... add your save logic here (API calls, etc.)
};

Adjust the initial value of confirmedRecord based on whether your app starts in edit mode or not.

Quick Tip

If you're using a different observable for edit state (like isEditing instead of confirmedRecord), just swap that in wherever you see confirmedRecord() in the code above.

内容的提问来源于stack exchange,提问作者shweta ghuge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:13:20