So here's what I'm trying to do, I have a button that I want to add an external HTML fragment when it is clicked for the first time. Then have that same fragment removed when that same button is clicked a second time. I'm very new to jQuery so I've been having trouble with this.
You can view the full code here: http://jsfiddle.net/jhoffm34/6xLw8/ , but here's the jQuery code I have so far. I know I'm going about this the wrong way, but I don't know how to fix it.
$.get("fragment.html", function(data) {
$('.js-load__button').click(function(){
$('#js-load').append(data);
$('.js-load__button').addClass("js-load__remove");
$('.js-load__button').attr("disabled", true);
});
$('.js-load__remove').click(function(){
$(data).remove();
$('.js-load__button').attr("disabled", false);
});
});
That code is a bit messy. If you organize things a little differently, it becomes pretty straightforward.
First. a more simplified HTML:
<ul id="list">
<li>
<figure>
<img src="http://placekitten.com/300/200"/>
<figcaption>I Can Haz Kitty?</figcaption>
</figure>
</li>
<li>
<figure>
<img src="http://placekitten.com/300/200"/>
<figcaption>I Can Haz Kitty?</figcaption>
</figure>
</li>
</ul>
<button>LOAD MORE</button>
Then here's the scripting to go along with it:
var list = document.getElementById('list');
var htmlFragment = '<li class="more"><figure><img src=\"http://placekitten.com/300/200\"/><figcaption>I Can Haz Kitty?</figcaption></figure></li>';
$('button').click(function(evt) {
evt.preventDefault();
var more = $(list).find('li.more');
if (more.length > 0) {
more.each(function() { $(this).remove(); });
} else {
$(htmlFragment).appendTo($(list));
}
});
Because I don't have access to your AJAX call, I just assume some sort of HTML string is returned as 'htmlFragment'.
I forked your fiddle and updated it here: http://jsfiddle.net/ToddT/XHNrM/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.