2011-09-06 2 views
1

첫째, jsfiddle ... 이제 http://jsfiddle.net/therocketforever/jYba3/11/jQuery로 배경색을 변경 한 후 재설정하는 방법은 무엇입니까?

// Highlight selected linker link & set all others to default. 
    $('a.linker').click(function(){ 
    $(this).addClass('selected'); 
    $(this).parent('li').siblings().find('.selected').removeClass('selected'); 

// Selects a random colour from the 'colors' array by getting a random value 
// between 0 and the length of the color array. 
    rand = Math.floor(Math.random()*colors.length); 
    $(this).css("background-color", colors[rand]); 

질문하기,

는 첫째로이 코드는 거의 정확하게 내가 사용자는 링크, 선택한 색상을 클릭, 그것을 원하는 방식으로 작동 링크 텍스트에 적용되고 다른 링크는 제거됨 & 링크 배경이 색상 배열에서 임의의 색상으로 설정됩니다. 시원한.

내가 알고 싶은 것은 ... 무작위로 설정된 배경색이 선택되지 않은 링크 (예 : .selected 클래스의 링크에만 배경색이 있습니다.)에서 제거되도록하려면 어떻게해야합니까?

같은 배경 색상이 두 번 연속 사용되지 않습니다

Bonas 포인트 경우 EXTRA CREDIT. .. (즉, 노란색 하나 개의 세트를 클릭하여 두 개의 노란색 제외한 다른 색상을 클릭하면

답변

1

이 모든 요구 사항을 충족 것을 (보너스 .)가 포함

$(document).ready(function(){ 

// Colours for links 
var colors = ["#fff766","#66cef5","#bd7ebc","#66cc66"]; 

$("a.linker").click(function(){   
    var $this = $(this).addClass("selected"); 

    $this.parent('li').siblings().find('.selected') 
     .removeClass('selected').css("background-color", ""); 

    var num = $this.data("colorNum"), 
     rand = num; 

    while (num === rand) { 
     rand = Math.floor(Math.random()*colors.length); 
    } 

    $this.css("background-color", colors[rand]) 
     .data("colorNum", rand); 
    }); 
}); 
1

을 그냥 배경색 제거하는 jQuery의 .css() 방법을 사용하십시오

$(this).addClass('selected') 
    .parent('li').siblings().find('.selected') 
    .removeClass('selected').css('background-color', ''); 
+0

@pimvdb :'.siblings()'는'this'를 포함하지 않을 것입니다. 그래서 우리는'selected' 클래스를 갖는'this'로 끝날 것이고, 다른 링크 ('li a')는 그렇지 않을 것입니다. –

+0

방금 ​​알아 챘습니다. 미안 해요. 신경 쓰지 마. – pimvdb

1

을 그냥 쓰기 :

$(this).css({'background-color':''}); 
+1

제목에 대한 완벽한 대답이기 때문에 나는 그것을 upvoted. 마우스 위치에서 색상을 변경 한 후 mouseleave 이벤트에서 필요한 것입니다. – edj

관련 문제