Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将类()添加到包含包装器中的特定元素_Javascript_Jquery_Addclass_Jquery Hover - Fatal编程技术网

Javascript 将类()添加到包含包装器中的特定元素

Javascript 将类()添加到包含包装器中的特定元素,javascript,jquery,addclass,jquery-hover,Javascript,Jquery,Addclass,Jquery Hover,我一直在绞尽脑汁想如何做到这一点。我有一个包含元素,其中有两个独立的a标记,我想addClass()将它们添加到其中(即,当我将鼠标悬停在一个a标记上时,它将类添加到该元素中,并将另一个a标记添加到该包含元素中)。我通过使用下面的代码获得了它: <li class="element"> <header> <h1>Heading</h1> </header> <a href=""> <img sr

我一直在绞尽脑汁想如何做到这一点。我有一个包含元素,其中有两个独立的
a
标记,我想
addClass()
将它们添加到其中(即,当我将鼠标悬停在一个
a
标记上时,它将类添加到该元素中,并将另一个
a
标记添加到该包含元素中)。我通过使用下面的代码获得了它:

<li class="element">
<header>
   <h1>Heading</h1>
</header>
   <a href="">
      <img src="image" alt=" dummy" />
   </a>
   <div>
      <h2><a href="">Heading 2</a></h2>
      <p>Paragraph</p>
   </div>
</li>

$('.element').hover(
 function() {
  $(this).children().addClass('hover');
},
 function() {
  $(this).children().removeClass('hover');
}
);
它只将类添加到第一个“a”标记

如有任何建议,将不胜感激

$('.element a').hover(
 function() {
  $(this).add($(this).siblings()).addClass('hover');
},
 function() {
  $(this).add($(this).siblings()).removeClass('hover');
}
);

$(此)仅包含悬停的实际对象。I.add()-将对象的同级添加到该集合中,如果愿意,可以使用$(this.sillides('a')或类似项对其进行筛选。

您需要将addClass应用于每个元素。。。试试这个:

$('.element a').each(function() {
    $(this).hover(function() {
        $(".element a").each(function() {
            $(this).addClass('hover');
        });
    }, function() {
        $(".element a").each(function() {
            $(this).removeClass('hover');
        });

    });
});

为什么不使用css选择器
a:hover
?示例用法->我不能使用hover函数,因为我需要在所有a元素上触发类,即使我在其中一个元素上悬停。了解-删除我的答案更新我的答案,我想这就是你想要的?这就快到了!唯一的问题是当您将鼠标悬停在a上时,它会将鼠标悬停应用于div,而不是其中的a。我尝试指定$(this).sibbines('a')解决方案,但没有效果。不完全-这会将类添加到页面上的每个“.element a”,而不是特定的列表项中。@Michael关于这个问题,您没有提到class元素有多个div?!?!?!抱歉-我认为这是一个列表元素,它将指示多个元素,但我应该更具体。我认为下面的答案非常接近我需要的,但就是无法得到嵌套的“a”标记。
$('.element a').each(function() {
    $(this).hover(function() {
        $(".element a").each(function() {
            $(this).addClass('hover');
        });
    }, function() {
        $(".element a").each(function() {
            $(this).removeClass('hover');
        });

    });
});