开发者

Help with removing element from list using jquery

I have a list:

<ul id="links_list" class="links_list">

<li id="296" class="sidebar_link">text
    <a onclick="deleteLink(296)" href="javascript:void(0);">Delete Link</a>
</li>

<li id="297" class="sidebar_link">text2
    <a onclick="deleteLink(297)" href="javascript:void(0);">Delete Link</a>
</li>

    ... etc for a long list of items ...

</u开发者_高级运维l>

I'm currently able to remove the first element using this:

function deleteFirst() {

... do ajax stuff ..

$('ul.links_list li:first-child').fadeTo("fast", 0.01, function(){ //fade
    $(this).slideUp("fast", function() { //slide up
        $(this).remove(); //then remove from the DOM
    });

});

}

How can I modify this function to allow me to delete any item in the list?


Instead of $('ul.links_list li:first-child') use $('ul.links_list li#' + itemID) and pass the itemID through the delete function.


I would bind all the links at once instead of inline, like this:

<ul id="links_list" class="links_list">
  <li data-id="296" class="sidebar_link">text
    <a href="#">Delete Link</a>
  </li>
  <li data-id="297" class="sidebar_link">text2
    <a href="#">Delete Link</a>
  </li>
</ul>

Then script like this:

$('#links_list li a').click(function(e) {
  var id = $(this).closest("li").attr("data-id");
  //do ajax stuff
  $(this).closest("li").fadeTo("fast", 0.01).slideUp("fast", function() {
    $(this).remove();
  });
  e.preventDefault(); //prevent page scrolling with # href
});

This fixes a few issues and some improvements:

  • IDs can't start with a number unless you're using HTML5
  • Markup is much lighter (you can probably remove the classes too)
  • .slideUp() is a queued animation same as .fadeTo(), no need to use a callback for it
  • The ID is gotten relatively, no more in-line script, easier to maintain and in another file

You can test it out here.


:nth-child Selector

See http://api.jquery.com/nth-child-selector/

For example :

$('ul.links_list li:nth-child(10)')


You could change your HTML to pass a reference to the one that was clicked, then use that reference.

HTML

<li id="296" class="sidebar_link">text
    <a onclick="deleteLink(this)" href="javascript:void(0);">Delete Link</a>
</li>
<li id="297" class="sidebar_link">text2
    <a onclick="deleteLink(this)" href="javascript:void(0);">Delete Link</a>
</li>

javascript

function deleteLink( elem ) {
    $( elem.parentNode ).fadeTo("fast", 0.01, function() { //fade
        $(this).slideUp("fast", function() { //slide up
            $(this).remove(); //then remove from the DOM
        });
    });
}​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜