简体   繁体   中英

List item selector without item with specific class

I have following list

<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>

I want to add class item-over on mouseenter and want to remove class item-over on

mouseleave without item which has class item-selected

I have tried

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

But unable.

How can do it?

I'd use the function to make doubly sure, I'd also use hover to make it more exciting and fun:

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

What it seems you have missed the doc ready handler for this, try putting it in document ready block:

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

it seems like your code is just fine, on the event side.

look at http://jsfiddle.net/F8rxJ/

this is the code:

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

});

it shows you that the event is working.

try to use "hover" on your real work you try to do.

Actually you don't need a JavaScript for this.

#myList li {
    &:hover {
        color: blue;
    }

    &.item-selected,
    &.item-selected:hover {
        color: red;
    }
}

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


or for IE >= 8

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

    &.item-selected {
        color: red;
    }
}

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

This is working

$('#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'); 
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM