2009-12-08 120 views
0

我有一些java腳本工作在導航菜單後面,用戶單擊導航按鈕,並且一些AJAX觸發並引入一些HTML,我想要的是如果再次單擊相同的鏈接,則由該特定按鈕加載的內容將從標記中移除。刪除javascript創建的內容

有沒有人有想法?我的代碼目前爲

$("#Blog").click(function (ev) { 
     ev.preventDefault() 
      var url = $(this).attr("href"); 
      $.ajax ({ 
       url: "index.php/home/category", 
       type: "GET", 
       success : function (html) { 
      //alert("Success"); 
        $("#accordion").append(html); 
       } 
      }); 
     }); 

回答

0
$("#accordion").append(
    $("<div class='AJAXContend' />").append(html) 
); 

然後你就可以輕鬆做到$('.AJAXContend').remove();

另一種選擇是做$('#accordion :last-child').remove();,但這是有點哈克。

0
$("#Blog").click(function (ev) { 
     ev.preventDefault(); 

缺少的preventDefault後面的逗號。

+0

這是一個分號,它是可選的(雖然使用良好的做法) – Greg 2009-12-08 12:00:26

+0

是啊,你是對的,該死的英語技能。 – yoda 2009-12-08 12:17:10

0

所以我不知道jQuery足以以這種方式回答,但爲什麼不使用簡單的布爾開關?

// Pseudo: 
If clicked and the switch is false, show the HTML, and set the Switch to True 

If clicked and the switch is true, hide the HTML, and set the Switch to False 

這應該解決問題。

下面的代碼可能是可怕的錯誤,但我會用它來解釋我的想法:

//Global Variables 
var switch = false; 

//Function 
if(!switch) 
{ 
    $("#Blog").click(function (ev) { 
     ev.preventDefault() 
      var url = $(this).attr("href"); 
      $.ajax ({ 
       url: "index.php/home/category", 
       type: "GET", 
       success : function (html) { 
       //alert("Success"); 
        $("#accordion").append(html); 
       } 
      }); 
     }); 

    switch = true; 
} 
else 
{ 
    $("#accordion").innerHTML = ""; 
    switch = false; 
} 
3

嘗試使用.toggle代替。點擊的:

這將允許你添加第二個功能當再次點擊按鈕時刪除內容。

$("#Blog").toggle(function (ev) { 
    ev.preventDefault(); 
    var url = $(this).attr("href"); 
    $.ajax ({ 
     url: "index.php/home/category", 
     type: "GET", 
     success : function (html) { 
      //alert("Success"); 
      $("#accordion").append(html); 
      } 
     }); 
    }, 
    function (ev) { 
     // remove content from accordion here 
    }); 
+0

好主意。我從來沒有發現'toggle'的好用... – Kobi 2009-12-08 11:59:35

+0

切換腳本,錯誤控制檯告訴我(ev)未定義 – Udders 2009-12-08 13:39:30

+0

這些示例沒有提到切換回調的事件對象。我在一個簡單的實驗中測試了它,它似乎對我有用。 '$('h1')。toggle(function(ev){ev.preventDefault(); alert(ev)},/ *第二個函數* /);' – 2009-12-09 11:37:37