2014-09-05 44 views
0

請檢查下面的jsfiddle:http://jsfiddle.net/yv8h8hca/1/淘汰賽:編程選擇行和數據錄入過程中設置重點

來源後: Highlight selected row using knockout

下已經發生:

  1. 行被選定元件。
  2. 行可以更新。
  3. 行可以添加到數組中。

我希望用戶能夠在一行中填寫數據,然後按下更新按鈕以自動選擇新行(使用現有的黃色背景)並將焦點設置爲ID列設置它準備編輯。

我想避免讓用戶用鼠標點擊新行來選擇它。

HTML:

<table class="defaultGrid"> 
    <thead> 
     <tr> 
      <td> 
       <button class="btn" data-bind="click: NewDetail">New</button> 
      </td> 
     </tr> 
     <tr> 
      <th>ID</th> 
      <th>Name</th> 
     </tr> 
    </thead> 
    <tbody data-bind="foreach: model.Things"> 
     <tr data-bind="click: $root.selectThing, css: { selected: isSelected} "> 
      <td> 
       <input type="text" data-bind="value: ID"> 
      </td> 
      <td> 
       <input type="text" data-bind="value: Name"> 
      </td> 
      <td> 
       <button style="width:60px" data-bind="click: $parent.UpdateDetail">Update</button> 
      </td> 
      <td> 
       <button style="width:64px" data-bind="click: $parent.RemoveDetail">Remove</button> 
      </td> 
     </tr> 
    </tbody> 
</table> 

的JavaScript:

$(function() { 
    Thing = function (id, name, selected) { 

     var self = this; 
     self.ID = id, 
     self.Name = name, 
     self.isSelected = ko.computed(function() { 
      return selected() === self; 

     }); 
    }; 

    function viewModel() { 
     var self = this; 
     self.model = {}; 
     self.model.CurrentDisplayThing = ko.observable(); 
     self.model.Things = ko.observableArray(
     [ 
     new Thing(1, "Thing 1", self.model.CurrentDisplayThing), 
     new Thing(2, "Thing 2", self.model.CurrentDisplayThing), 
     new Thing(3, "Thing 3", self.model.CurrentDisplayThing)]); 
     self.selectThing = function (item) { 
      self.model.CurrentDisplayThing(item); 
     }; 

     this.NewDetail = function() { 
      var item = new Thing(4, "Thing 4", self.model.CurrentDisplayThing); 
      self.model.Things.push(item); 
      self.model.CurrentDisplayThing(item); 
     }; 

     // Update NVD 
     this.UpdateDetail = function (entry) { 
      // code to update detail.... 

      // Now, create new row for next input 

      var item = new Thing(entry.ID + 1, "", self.model.CurrentDisplayThing); 
      self.model.Things.push(item); 
      self.model.CurrentDisplayThing(item); 
     }; 

     self.RemoveDetail = function (entry) { 
      self.model.Things.remove(entry); 
     }; 
    } 
    ko.applyBindings(new viewModel()); 
}); 
+0

爲什麼是「更新」,並稱新行? – haim770 2014-09-05 06:59:21

+0

這是爲了快速輸入數據。用戶可能需要輸入數百行。所以,在更新當前行後,我們爲下一行設置數據輸入。我想盡可能避免在這裏使用鼠標。我知道表單上的添加新按鈕,但同樣,在您鍵入時創建新行以保持數據輸入流將會很好。 – user1309226 2014-09-05 07:04:03

+0

我現在遇到的問題是,除非您用鼠標單擊一行,否則無法選擇它。由於按下「更新」按鈕,我希望能夠在創建後選擇一行。 – user1309226 2014-09-05 07:13:17

回答

0

要選擇新行我不得不停止冒泡否則會選擇點擊的地方保存按鈕行的行單擊事件。

<td><button style="width:60px" data-bind="event: {click : $parent.Detail }, clickBubble: false">Save</button></td> 

要設置編輯模式我設置hasfocus數據綁定屬性:

<td><input type="text" class="nvd" data-bind="value: ID, hasfocus: isNew"></td>