开发者

jquery list confusion

I'm a new to the jQuery world and I'm having a problem that I just can't solve. I have an unordered list with multipl开发者_Go百科e li's. I'm trying to make it so when the user clicks a row, the bg color on the row changes. And when another row is click, that row's bg color changes and the previous on goes back to the default color. This is my code so far:

$('.allVideos ul li').hover(function(){
   $(this).css('background','#c7f1f2');
}, function(){
   $(":not($(this))").css('background','');
});

Unfortunately it isn't working as planned. Can anyone explain to me what I am doing wrong?

Thanks


this will work ,

$('.allVideos ul li').click(function(){

   $(".allVideos ul li").not($(this)).css('background','');
   $(this).css('background','#c7f1f2');
});


You want to use the not filter, not the :not selector:

$('li').click(function() {
    $(this).css('background-color', '#c7f1f2');
    $('li').not(this).css('background-color', '');
});

Demo: http://jsfiddle.net/ambiguous/ZUk88/

When you say li:not($(this)) then you're trying to select all <li> elements that aren't <$(this)> elements and that doesn't make sense; similarly for li:not(this).

You could also remove the background color from all the list items and then add it to the one you want:

$('li').click(function() {
    $('li').css('background-color', '');
    $(this).css('background-color', '#c7f1f2');
});

Demo: http://jsfiddle.net/ambiguous/L6ZNz/

Also, your question talks about clicking but your code talks about hovering.


If you have colors already attached to your <li> elements and you want to restore those colors when someone clicks another <li>, then you should just add and remove a CSS class to change the color. A bit of CSS:

.hilight {
    background-color: #c7f1f2 !important;
}

and some jQuery:

$('li').click(function() {
    $(this).siblings('.hilight').removeClass('hilight');
    $(this).addClass('hilight');
});

Demo: http://jsfiddle.net/ambiguous/ZJpNa/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜