2

我是 jQuery 新手,我在 Stack 上搜索过类似的问题,但没有找到这个特定的(而且我确定很常见)问题。

我有一个具有默认类的项目列表。我想使用 toggleClass 添加翻转效果。问题是所有的 lis 都获得了切换的类,而不仅仅是悬停的类。

<ul>
 <li class="my-class"><div id="my-item>1</div></li>
 <li class="my-class"><div id="my-item>2</div></li>
 <li class="my-class"><div id="my-item>3/div></li>
</ul>

$('.my-class, li').on('mouseenter', function() {
    $('#my-item').toggleClass('project-home-title-hover');
});
4

1 回答 1

3

Scope the selector with this. Also remove the comma between .my-class and li and change the selector to li.myclass. Also my-item should be a class instead of an id, ids must be unique. The markup also need some work there are unclosed end tags for one of the divs and missing quotes.

$('li.my-class').on('mouseenter  mouseleave', function() {
    $('.my-item', this).toggleClass('project-home-title-hover');
});

HTML

<ul>
 <li class="my-class"><div class="my-item">1</div></li>
 <li class="my-class"><div class="my-item">2</div></li>
 <li class="my-class"><div class="my-item">3</div></li>
</ul>

Js Fiddle: http://jsfiddle.net/SEMKr/1/

于 2013-09-05T23:53:10.823 回答