2011-12-07 78 views
5

好吧,我正在製作一個插件,允許在我的網站中進行表格的內聯編輯,到目前爲止效果很好,我已經完成了大部分工作,但似乎無法獲得專注於表格的權利。因此,如果有人正在編輯並開始編輯新行,或者只是點擊了該行,則應該保存並恢復正常。但如果我在該行上使用模糊,則沒有響應,但如果我在元素上使用模糊,則會在人們從一個元素交換到另一個時觸發jQuery - 聚焦於TR

但是,如果我在行上使用聚焦,該元素也是如此,即使他們點擊了同一行。在事件變量下面也沒有任何東西告訴我它將焦點放在哪個元素上,所以我無法與當前行進行比較,看它們是否只是在該行中單擊。

我在考慮讓它保存在Enter/Mouse上點擊保存按鈕/開始編輯另一行,但我寧願讓它工作,因爲它似乎是一個更好的方法。認爲任何人?請?

+0

你可以張貼一些示例標記? – kinakuta

回答

3

我會處理您的請求:僞代碼可能工作是這樣的。我設置一個小提琴證明:http://jsfiddle.net/NwftK/

<table border="1" width="200"> 
    <tr id="myRow"><td>Hello</td><td>World</td></tr> 
</table> 

而jQuery的:

$(function() { 
    $("#myRow").on('click', function (e) { 
     $(this).css('background-color', 'blue'); 
     e.stopPropagation(); 
    }); 

    $(document).on('click', function() { 

     $("#myRow").css('background-color', 'red'); 
    }); 

}); 
+0

謝謝,我可能會用這個 –

1

問題是即使您有嵌套元素,當您關注其中一個子元素時,focusout也會在父元素上觸發。我能想到的解決方案是使用變量來跟蹤當前行。通過結合一個單擊處理整個文檔,然後將我的其他點擊事件中的stopPropagation()調用

var row = ''; 
$(table_element).click(function() { 
          focused_row = $(this).parent(); 
          if(row != '' && focused_row != row) { 
           //code to save edits, user clicked different row 
          } 
          row = focused_row; 
         }); 
+0

我在想那個,但是如果他們點擊桌子外面,它不會保存 –

0

有2情況下,您需要在該行失去焦點,而你是在表內進行檢測,一和兩個當你離開桌子。

你可以嘗試這樣的事情:

//store the last visited row 
var row = false; 

// save the row if has changed 
function save() { 
    if (row.changed){ 
     console.log("save"); 
    } 
} 

// keep track of the row you are in 
// it doesnt work when you leave the table 
$("tr").on("focusin", function (e) { 
    if (row != this){ 
     if (row){ 
      save(); 
     } 
     row = this; 
     e.stopPropagation(); 
    } 
}); 

//keep track whenever the row changes 
$("tr").on("change", function (e) { 
    this.changed = true; 
    console.log("changed"); 
}) 

//triggers when you leave the table, you can try to save changes then. 
$(document).on("focusin", function (e) { 
    var el = $(e.target); //input or element that triggers this event 
    var elrow = el.parent().parent()[0]; // try to get the row from that input, ... if its an input 
    if (row && row !=elrow) { 
     save(); 
     e.stopPropagation(); 
    }; 
})