2010-01-10 273 views
2

高!

我想要做的是以下幾點:我有一個表連接到位於偶數行表中的鏈接的onclick。每一行都是隱藏的。點擊該鏈接時,會顯示奇數行並將數據加載到該行中。工作正常

現在我想要做的是,無論何時該過程完成,我想附加一個新的點擊功能,使該行再次隱藏的鏈接。有點像切換,但隨着一些更只是顯示/隱藏功能。我試圖用下面的代碼做到這一點,但無法讓它工作。我肯定會錯過一些非常基本的東西,或者只是不太瞭解jquery(這很可能,因爲我剛剛開始幾周前)。

$(document).ready(function(){ 

    // The version icons 
    $("a.version").click(function() { 
     var sLink = $(this).attr("href"); 
     var nexttr = $(this).parent().parent().next("tr.version"); 
     var nexttrtd = nexttr.find("td:first"); 
     $.get(sLink, function(sData){ 
      nexttrtd.html(sData); 
      nexttr.show(); 
     }); 

     $(this).click(function(){ 
      attachHideMyChildren(); 
     }); 

     return false; 
    }); 
}); 

function attachShowMyChildren() 
{ 
    var sLink = $(this).attr("href"); 
    var nexttr = $(this).parent().parent().next("tr.version"); 
    var nexttrtd = nexttr.find("td:first"); 
    $.get(sLink, function(sData){ 
     nexttrtd.html(sData); 
     nexttr.show(); 
    }); 
    $(this).click(function(){ 
     attachHideMyChildren(); 
    }); 
    return false; 
} 

function attachHideMyChildren() 
{ 
    $(this).parent().parent().next("tr.version").hide(); 
    $(this).click(function(){ 
     attachShowMyChildren(); 
    }); 
} 

它打開表格行,插入數據然後再附加函數關閉行。我怎麼能得到這個發生?

任何想法?

回答

5

問題是這樣的:

$(this).click(function(){ 
    attachHideMyChildren(); 
}); 

當你調用方式this成爲window功能。相反,這樣做:

$(this).click(attachHideMyChildren); 

另外,您要添加click()處理程序不刪除舊的。

這就是說,有一個更簡單的方法來做到這一點。

$("a.version").click(function() { 
    var next = $(this).closest("tr").next(); 
    if (next.is(":hidden")) { 
    $.get($(this).attr("href"), function(sData) { 
     next.find("td:first").html(sData); 
     next.show(); 
    }); 
    } else { 
    next.hide(); 
    } 
    return false; 
}); 

應該這樣做。

+0

聖潔的廢話!它做到了。謝謝cletus。 – 2010-01-10 12:03:27