2012-04-17 137 views
0

這個問題可能是重複的(但我找不到它),所以如果它是多餘的,我很抱歉。我正在嘗試使用JQuery的.remove函數來刪除(顯然)我的靜態HTML原型中的li元素。而不是爲每個li寫出一個JavaScript塊,我想刪除我想知道是否有可能創建單獨的JS增量ID。 (我使用Serve與HAML和SASS fyi)。這是我的。用JQuery創建唯一ID

/view-file.html.haml

%ul 
    %li#removeThis1 
    %a.remover1{:src => "#"} Remove 

/application.js

... 
$(".remover1").click(function() { 
    $("li#removeThis1").fadeOut(function() { $(this).remove(); }); 
}); 

如何增加.remover1.remover2任何想法,等?同樣li##removeThis1#removeThis2

我會需要所有這些發生在頁面加載。

+2

可能重複的[jquery創建一個唯一的id](http://stackoverflow.com/questions/1817114/jquery-create-a-unique-id) – 2012-04-17 03:31:25

+0

你可以顯示生成的HTML,讓不知道的人哈姆可以提供一些幫助? – jfriend00 2012-04-17 03:36:25

回答

2

元素之間有一種祖先關係,所以只要使用它就可以獲得優勢。

// don't bother numbering the class. Use a common class 
$(".remover").click(function() { 

     // find the closest ancestor with an ID that start with "removeThis" 
    $(this).closest("li[id^=removeThis]") 
      .fadeOut(function() { $(this).remove(); }); 
}); 

或者,如果你並不真正需要的祖先的ID,使用類有太多...

// don't bother numbering the class. Use a common class 
$(".remover").click(function() { 

     // find the closest ancestor with the class "removeThis" 
    $(this).closest(".removeThis") 
      .fadeOut(function() { $(this).remove(); }); 
}); 

最後,如果你使用的ID ,你需要在服務器端生成它們,然後使用處理程序從元素中提取ID的數字部分,並將其連接到祖先的選擇器中。

+0

只是好奇,爲什麼你的大部分答案都標記爲「社區維基」? :o – 2012-04-17 03:36:51

+0

@NiftyDude:主要是因爲我不喜歡/想要代表點。但也可以讓其他人覺得如果他們願意,可以增加價值/更正。 – 2012-04-17 03:39:05

+1

這對你很好:) – 2012-04-17 03:39:52