列表项选择器,不带具有特定类的项

List item selector without item with specific class

本文关键字:选择器 列表      更新时间:2023-09-26

>我有以下列表

<ul id='myList'>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li class='item-selected'>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
</ul>

我想在mouseenter上添加类item-over,并希望删除类item-over

mouseleave没有具有类 item-selected 的项目

我试过了

$('#myList li:not(".item-selected")')
    .mouseenter(function(){ 
         $(this).addClass('item-over'); 
    })
    .mouseleave(function() {
         $(this).removeClass('item-over'); 
    });

但不能。

怎么能做到?

我会使用这个函数来加倍确定,我也会使用hover来让它更令人兴奋和有趣:

$('#myList li').not( ".item-selected" ).hover(
     function(){ 
         $(this).addClass('item-over'); 
     },
     function() {
          $(this).removeClass('item-over'); 
     }
);

您似乎错过了doc ready处理程序,请尝试将其放入文档就绪块中:

$(function(){
    $('#myList li:not(".item-selected")').mouseenter(function(){ 
        $(this).addClass('item-over'); 
    }).mouseleave(function() {
        $(this).removeClass('item-over'); 
    });
});

事件方面,您的代码似乎很好。

看看 http://jsfiddle.net/F8rxJ/

这是代码:

$(document).ready(function () {
    $('#myList li:not(".item-selected")').bind('click',function(){
        alert('xxx');            
    });
});

它显示事件正在运行。

尝试在你尝试做的实际工作上使用"悬停"。

实际上你不需要JavaScript

#myList li {
    &:hover {
        color: blue;
    }
    &.item-selected,
    &.item-selected:hover {
        color: red;
    }
}

http://jsfiddle.net/f0t0n/xGqeE/


或对于 IE>= 8

#myList li {
    &:hover:not(.item-selected) {
        color: blue;
    }
    &.item-selected {
        color: red;
    }
}

http://jsfiddle.net/f0t0n/LBULM/

这是有效的

$('#myList li:not(".item-selected")')
    .mouseenter(function(){ 
         if(!$(this).hasClass("item-selected")) //added this line
             $(this).addClass('item-over'); 
    })
    .mouseleave(function() {
         $(this).removeClass('item-over'); 
    });