jQuery Append and Remove
I am trying to use this jQuery to append some HTML and then unappend it
if( !(jQuery(check).hasClass('selected'))){
jQuery(this).append('<span class="selected"> </span>');
}
How am I able to do this and also live update it ? I am just trying to add this element when a user "clicks" on or "of开发者_运维百科f" ?
i.e. if check does not have the class "Selected" - append - else remove ?
Since your question was kind of vague and lacked markup I used a basic checkbox example for the demo. I've included a link to a live demo at jsFiddle here
HTML:
<input type="checkbox" id="test" /> Check me
<div id="items"></div>
JavaScript:
$("#test").bind('click', function(){
var $t = $(this);
if($t.is(':checked')){
// append item
$('#items').append('<span class="selected">I was recently appended.</span>');
}else{
// empty div and remove it from DOM (empty helps with memory leak issues with remove() )
$('span', '#items').empty().remove();
}
});
I believe a more better approach might be to store the result of each append to an array or a variable and loop through that when you remove the elements. For a single element,
// Appending
var ele = $('<span>', {
html: 'nbsp;',
class: 'selected'
}).appendTo(container);
// Removing
ele.remove();
If you're doing this from within an event handler, the variable ele
should be defined in the outside scope, so that it is accessible afterwards. For multiple items:
// Appending
var ele = [];
ele.push($('<span>', {
html: 'nbsp;',
class: 'selected'
}).appendTo(container));
// Removing
for(var i = 0; i < ele.length; i++){
ele[i].remove();
}
Again, the array ele
should be defined outside of the scope of any event handlers. Otherwise, the other answers to this question will work too.
jQuery('#check').click(function() {
var check = jQuery(this);
if ( !check.hasClass('selected') ) {
jQuery('#mydiv').append('<span class="selected"> </span>');
check.addClass('selected');
} else {
jQuery('#mydiv span.selected').remove();
check.removeClass('selected');
}
});
I think you don't need to add span tag there. then, the code can be short like this.
$("#check").click(function(){
$(this).hasClass('selected') ? $(this).removeClass('selected') : $(this).addClass('selected');
});
精彩评论