2010-04-04 181 views
1

我對jQuery一無所知,但我是一名經驗豐富的C++程序員(不確定是否有幫助或傷害)。我找到了jQuery代碼,當用戶單擊該單元格時,該代碼爲我提供HTML表格中單元格的行和列索引。使用這樣的行列索引號,我需要更改之前選擇的單元格和剛剛單擊的單元格中的屬性值。索引編號與此代碼生成並保存:如果我知道單元格的行和列索引,如何更改HTML表格單元格中的屬性?

var $trCurrent = 0; // Index of cell selected when page opens 
var $tdCurrent = 0; // i.e., previously selected cell 

$(document).ready(function() 
{ 
    $("td").click(function() 
    { 
     // How toclear previously selected cell's attribute here? ('class', 'recent') 
     var oTr = $(this).parents("tr"); 
     $tdCurrent = oTr.children("td").index(this); 

    }); 
    $("tr").click(function() 
    { 
     $trCurrent = $(this)[0].rowIndex; 
     // How to set new attributes here? ('class', 'current'); 
     // and continue work using information from currently selected cell 

    }); 
}); 

任何幫助或提示將不勝感激。我甚至不知道這是否應該得到行和列的索引。

回答

5

如果我瞭解您的要求,我會做這個略有不同的事情。如果當你點擊一個單元時,你需要對之前單擊的單元做些什麼,請使用一個類。所以:

$("td").click(function() { 
    $("td.active").removeClass("active"); 
    $(this).addClass("active"); 
}); 

所以每次基本上你單擊一個單元格,以前active細胞有其類中刪除,新的細胞有它補充說。在上面的代碼中,我刪除了類,你可以做任何你喜歡的東西,這可以避免存儲和引用行/單元格編號的問題。

如果你的目標很簡單,就是不同風格的小區,使用相同的類在你的CSS如:

td.active { background: yellow; } 

當你渲染頁面,你可以讓任何一個細胞,你喜歡主動通過賦予該類。

如果您需要了解當前和以前的細胞試試這個:

$("td").click(function() { 
    $("td.active").removeClass("current").addClass("previous"); 
    $(this).addClass("current"); 
}); 

然後在任何時候,你可以這樣做:

$("td.current")... 
$("td.previous")... 

如果你真的需要知道的行/手機號碼點擊試試:

var rownum; 
var cellnum; 
$("td").click(function() { 
    var row = $(this).closest("tr"); 
    rownum = $("tr").index(row); 
    cellnum = row.children("td").index(this); 
}); 

如果你需要引用任何一點:

$("tr:eq(" + rownum + ") > td:eq(" + cellnum + ")")... 
+0

@cletus,我認爲你很棒<3 – 2010-04-04 01:59:09

+0

Cletus,這是偉大的(而且很簡單)。謝謝! – Mark 2010-04-04 04:30:03

相關問題