how to remove anchor or add them in blank ul li using jQuery
I want to add an anchor in li and want to 开发者_如何学Goremove from another li but don't know how it can be done. Does anyone know how this is possible using jQuery?
add them in blank
<li>
<!-- i think to add the anchor here by many attribute --->
</li>
<li>
<!-- this anchor how i can remove -- >
<a></a>
</li>
the logic i want to do something like
when event fire :-
var cur = cur; // current is variable where i store li who i want to do.
how i can remove them from it and how i can add if they really have not anchor on them.
It's a bit unclear exactly what the requirement is, so some handy tips and a couple of examples to get you going:
1) To get a jQuery object for an element, use $
(aka jQuery
) and a CSS3 selector:
var $element = $("CSS3_selector_for_element");
2) To remove an element, use remove
:
$element.remove();
3) To detach an element (so you can put it back later without losing its event handlers, etc), use detach
:
$element.detach();
4) To add or move an element, use append
, appendTo
, before
, insertBefore
, after
, insertAfter
, or probably a few others (if you're moving it from somewhere else, no need to detach
it first):
$element.appendTo(target);
or
jquery_object_for_target.append($element);
Very basic example of moving li
s containing anchors from one list to another when the anchor is clicked:
HTML:
<ul id='first'>
<li><a href='#'>Anchor One</a></li>
<li><a href='#'>Anchor Two</a></li>
<li><a href='#'>Anchor Three</a></li>
</ul>
<hr>
<ul id='second'>
<li><a href='#'>Anchor Four</a></li>
<li><a href='#'>Anchor Five</a></li>
<li><a href='#'>Anchor Six</a></li>
</ul>
JavaScript using jQuery:
jQuery(function($) {
$("a").click(function() {
var $this, li, list, target;
$this = $(this);
li = $this.closest('li');
list = li.closest('ul');
target = list[0].id == 'first' ? '#second' : '#first';
$(target).append(li);
return false;
});
});
Live copy
If you prefer not to figure out where the li
is when the event first, you can use delegate
to watch the anchors inside a specific list (the HTML is the same as the above):
jQuery(function($) {
$("#first").delegate('a', 'click', function() {
return moveContainingListItemTo(this, '#second');
});
$("#second").delegate('a', 'click', function() {
return moveContainingListItemTo(this, '#first');
});
function moveContainingListItemTo(element, target) {
$(element).closest('li').appendTo(target);
return false;
}
});
Live copy
give some class name to that li and the do something like this...
$('li ').live('click', function () {
if(!jQuery("li').hasClass('selected')){
jQuery(this).addClass('selected').append('<a id="anchor">blah...</a>')
}else{
jQuery(this).removeClass('selected').find('a').remove();
}
});
精彩评论