2012-04-17 85 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