2009-07-13 78 views
29

卸下李我有一個無序列表:jQuery的從UL與超鏈接在李

<ul id="sortable"> 
    <li id="1" class="ui-state-default">First <a href='#' title='delete' class="itemDelete">x</a></li> 
    <li id="2" class="ui-state-default">Second <a href='#' title='delete' class="itemDelete">x</a></li> 
    <li id="3" class="ui-state-default">Third <a href='#' title='delete' class="itemDelete">x</a></li> 
</ul> 

我想從<ul>刪除<li>。我已經處理了類itemDelete的click事件,我嘗試去除它,但是我認爲它不起作用,因爲我無法在小孩調用它時刪除<li>

$('.itemDelete').live("click", function() { 
      var id = $(this).parent().get(0).id; 


      $("#" + id).remove(); 

     }); 

什麼是最好的方法呢?

+2

您的ID無效 - ID不能以數字開頭 – Greg 2009-07-13 14:56:34

+0

@Jon您的問題對我非常有幫助 – 2012-05-15 16:29:40

回答

56

假設你正在使用的是最新的jQuery的版本:(儘管parent作品在這裏也)

$('#sortable').on('click', '.itemDelete', function() { 
    $(this).closest('li').remove(); 
}); 

closest是多了幾分活力比parent它得到li最接近當前元素,在結構中向上。

6

你不必在你<li>小號

標識如何簡單地

$(this).parent().remove(); 
7

其實,你有它作爲現在的樣子,id將是不確定的,因爲沒有任何的李的有ID。

爲什麼不只是做

$(this).parent().remove() 

也不要忘了返回false。

+0

我確實有id的forgoto將它們粘貼到原始帖子 – Jon 2009-07-13 14:55:14

0

什麼清盤工作對我來說: 前綴您的ID與屬性字符串或下劃線(正如其他人所指出的)

由於像jQuery Mobile的框架要求,IDS是所有網頁上的唯一的(不只是在一個頁面上,我以頁面名稱,下劃線和數字ID作爲前綴,讓我訪問數據庫中的記錄。

而不是綁定到類或ul控件,使用'on'綁定到li母公司列表:

$('#sortable').on('dblclick', 'li' function() { 
     aval = $(this).attr('id').match(/\d+/g); // only want the numbers... 
     id = aval[0]; 
     name = $(this).text(); // in case you need these for a post... 
     li = $(this); // so we can remove it from the list after the 'this' object changes inside the ajax call... 
     // make an ajax call to the server 
     var jqxhr = $.post("somepage.php", {name: name, id: id}, 
      function(data) { 
      li.remove(); 
      $("#sortable").listview("refresh"); 
    },'json').fail(function() { alert("error"); }); 
    return false; // preventDefault doesn't seem to work as well... 
});