Removing javascript created content
I have some java script that work behind a navigation menu, the user clicks the nav button, and some AJAX fires and brings in some HTML, what I want is for if that same link is clicked again then the content that was loaded in by that specific button is removed from the markup.
Does anyone have ideas? My code currently stands at
$("#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);
}
});
});
Try using .toggle instead of .click:
This would allow you to add a second function which removes the content when the button is clicked again.
$("#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
});
$("#accordion").append(
$("<div class='AJAXContend' />").append(html)
);
And then you can easily do $('.AJAXContend').remove();
.
Another option is to do $('#accordion :last-child').remove();
, but this is a little hacky.
$("#Blog").click(function (ev) {
ev.preventDefault();
Missing the comma after preventDefault.
So I don't know jQuery enough to answer in that way, but why not use a simple boolean switch?
// 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
That should solve the problem.
The following code is probably horribly wrong, but I will use it to explain my thinking:
//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;
}
精彩评论