2012-05-01 25 views
0

我正在學習jQuery,並在before函數中遇到問題。我正在做的是我有一張fish的表格,使用detach將其刪除並放入一個數組中,這樣當我點擊一個按鈕時,它將恢復到原來的位置。這是我下面的內容。我試圖完成的最終結果是把文字(泛油炸比目魚)放回桌子。任何幫助是非常讚賞在jQuery中使用before函數

<table> 
    <tr> 
     <td>&nbsp;</td> 
     <td class="fish">Pan-Fried Halibut</td> 
     <td>&nbsp;</td> 
    </tr> 
</table> 

這裏是jQuery的分開函數:

$("input#btn1").click(function() { 
    $f = $(".fish").detach(); 
}); 

試圖把文本帶回:

$("input#btn2").click(function() { 
    $(".fish").first().before($f); 'This statement doesnt work; what am i doing wrong 
});        
+5

你的代碼有什麼問題?我們不介意讀者。 –

回答

0

目前尚不清楚你想什麼在這裏做。

一個問題是,在你做了$(".fish").detach()之後,魚類中的元素將不會保留在DOM樹中。因此,當你以後做$(".fish")什麼都不會匹​​配,因此什麼都不會插入。

另一個問題是,你似乎將click處理程序附加到相同的元素;當按鈕被點擊時,兩者都會被調用,並且最終的結果並不明顯。

最後,$f如何從第一個事件處理程序傳遞到第二個?

你會看到一些結果(可能不是你的,雖然意),如果你這樣做了:

$(function() { 
    var $f; // so that it's accessible to both event handlers 

    // bind two handlers to the click event, to be executed on alternating clicks 
    $("input#btn1").toggle(function() { 
     $f = $(".fish").detach(); 
    }, function() { 
     // you need to find some appropriate selector here, $(".fish") 
     // will match nothing because those elements have already been detached 
     $(/*something*/).first().before($f); 
    }); 
}); 
0

我不認爲可變$f還是在範圍上,當你想添加文本請嘗試這樣的代替:

$("input#btn1").click(function(){ 
    var $f = $(".fish").first(); 
    $(".fish").before($f); 
}); 
0

一旦你分離。魚,它不再存在。所以你不能參考它並嘗試把它放回去。嘗試通過提供一個不同的位置來恢復。試着看這個例子 - http://jsfiddle.net/mnNfH/