jquery从元素中选择一个特定的类

时间:2009-11-29 21:16:57

标签: jquery jquery-selectors

我正在尝试使用类名对相关元素进行分组。反过来,它们都是相关的,因为它们都使用相同的类名前缀。例如:

<ul>
  <li class="category-fruit"></li>
  <li class="category-grain"></li>
  <li class="category-meat"></li>
  <li class="category-fruit"></li>
  <li class="category-meat"></li>
</ul>

从视觉上来说,我希望每个悬停功能在悬停时,将相同的视觉效果应用于共享相同类名的其他元素。

虽然选择具有特定类的特定LI很容易,但我如何从悬停的LI中选择一个特定的类?

所以在伪代码中

$("li").hover(function(){
    $(this).[get-the-class-beggining-with"category"]
})

我猜这涉及到使用带有选择器的启动([attribute ^ = value])

2 个答案:

答案 0 :(得分:3)

您可以使用attributeStartsWith选择器:

$("li[class^=category]").hover(/*...*/);

使用您的标记here检查示例。

修改:要获取班级名称,您可以使用this.className或使用attr功能,例如:

$("li[class^=category]").each(function(){
  var className = $(this).attr('className');  
  // this.className, or attr('class'), which will be mapped to className
});

顺便说一下,您还可以使用filter(fn)方法选择其className以“category”开头的li元素:

$("li").filter(function () {
  return /category-.+/.test(this.className);
}).hover(/*...*/);

答案 1 :(得分:1)

关注@ CMS的精彩领导,我已经向JSBin发布了working example此解决方案。

我提出了一个解决方案,允许您在li's上添加其他类,并在找到正确的兄弟节点之后将其缓存以供将来使用以加快执行:

$(function(){
    $("li").hover(function(){
        var $this    = $(this),
            $cache   = $this.data('hoverCache');

        if(!$cache){
            var category = this.className.match(/category\-.+?\b/)      
            $this.data('hoverCache', $this.siblings('.' + category).andSelf().addClass('hover') );
        } else {
            $cache.addClass('hover');
        }

    }, function(){
        var $cache = $(this).data('hoverCache');
        if($cache) $cache.removeClass('hover');
    });
})

因此,在此优化示例中不会丢失,这是您问题的相关代码:

var category = this.className.match(/category\-.+?\b/);
$(this).siblings('.' + category).andSelf();

这可以从className中找到类别(可以有其他类),然后使用.siblings找到同一父级的其他子级,然后包含自己,这样就可以添加{{1}一次对元素进行类。

我使用Firefox和您提供的HTML测试了此代码,效果很好。如果它不是你需要的,请告诉我!

相关问题