[英]Append Fragment on first click then remove on second in jQuery
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. 因此,这就是我要尝试的操作,我有一个按钮,我想在第一次单击它时添加一个外部HTML片段。 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. 我对jQuery非常陌生,因此遇到了麻烦。
You can view the full code here: http://jsfiddle.net/jhoffm34/6xLw8/ , but here's the jQuery code I have so far. 您可以在此处查看完整的代码: http : //jsfiddle.net/jhoffm34/6xLw8/ ,但这是到目前为止的jQuery代码。 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: 更简化的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'. 因为我无权访问您的AJAX调用,所以我仅假设某种HTML字符串作为“ htmlFragment”返回。
I forked your fiddle and updated it here: http://jsfiddle.net/ToddT/XHNrM/ 我分叉了您的小提琴,并在此处进行了更新: http : //jsfiddle.net/ToddT/XHNrM/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.