2015-05-14 64 views
0

我有一個敲擊視圖模型函數,點擊按鈕時不會調用它。 可能我錯過了一些東西。我正在運行VS2010 IDE的代碼。我在jsfiddle和 測試相同的代碼,它在那裏工作,但是當我嘗試從VS2010 IDE運行相同的代碼,那麼它不工作。任何幫助 將不勝感激。謝謝點擊按鈕時不會調用knockoutjs函數

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
    <style type="text/css"> 
     #dash 
     { 
      max-height: 128px; 
      overflow: hidden; 
     } 
     #dash div 
     { 
      border: 1px solid #de2345; 
      padding: 4px; 
      margin: 2px; 
      line-height: 20px; 
      box-sizing: border-box; 
     } 
     #dash div:before 
     { 
      content: '--> '; 
     } 
    </style> 
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"/> 
    <script type="text/javascript"> 
     function TableModel() 
     { 
      var self = this; 
      self.Counter = 1; 
      self.rows = ko.observableArray([]), 
      self.addRow = function() { 
       alert('pp'); 
       self.rows.push(self.Counter + ' ' + new Date()); 
       self.Counter++; 
       setTimeout(function() { 
        self.rows.shift(); 
        self.Counter--; 
       }, 3000 + self.rows().length * 1000); 
       return false; 
      } 
     } 
     ko.applyBindings(new TableModel()); 
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <button id="button" data-bind="click: addRow" type="button">click</button> 

    <div id="dash" data-bind="foreach: rows"> 
     <div data-bind="text:$data"> 
     </div> 
    </div> 
    </form> 
</body> 
</html> 

回答

1

當加載DOM時必須調用ko.applyBindings。請參閱documentation

你可以做到這一點:

  • 把腳本塊在HTML文檔的底部,收盤前body
  • 您可以留下您的腳本在head secttion和包裝的調用``ko.applyBindings`在DOM就緒處理程序,如jQuery’s ready功能

如果你不使用jQuery只是移動你的腳本底部:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title>  
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <button id="button" data-bind="click: addRow" type="button">click</button> 

    <div id="dash" data-bind="foreach: rows"> 
     <div data-bind="text:$data"> 
     </div> 
    </div> 
    </form> 
    <script type="text/javascript"> 
     function TableModel() 
     { 
      var self = this; 
      self.Counter = 1; 
      self.rows = ko.observableArray([]), 
      self.addRow = function() { 
       alert('pp'); 
       self.rows.push(self.Counter + ' ' + new Date()); 
       self.Counter++; 
       setTimeout(function() { 
        self.rows.shift(); 
        self.Counter--; 
       }, 3000 + self.rows().length * 1000); 
       return false; 
      } 
     } 
     ko.applyBindings(new TableModel()); 
    </script> 
</body> 
</html> 
+0

我只是簡單地將你的代碼粘貼到我的aspx表單中並運行它。然後我發現頁面中沒有任何可見所以請嘗試首先在您的結尾運行您的代碼,並告訴我它是否按預期工作。 – Mou

+0

這是你原來的代碼中的另一個錯誤:腳本標籤不能被自封閉(http://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work)。因此,將您的第一個腳本元素更改爲''。我也更新了這是我的回答 – nemesv

+0

很好地注意到腳本標記。它會導致問題。非常感謝 :) – Mou