2009-12-08 45 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