2014-05-21 2 views
0

jQuery를 사용하여 검색 메뉴 버튼 내에 2 가지 종류의 피드백을 프로그래밍하려고합니다. 문제는 2가 충돌하는 코드를 필요로한다는 것입니다.jquery 함수의 우선 순위를 지정하여 다른 함수를 재정의

먼저 마우스를 입력 할 때 빨간색 버튼을 다른 색상 (파란색)으로 변경 한 다음 빨간색 버튼을 원래 색상 마우스가 단풍 (빨간색) :

$('.buttons').mouseenter(function() { 
    $(this).css("background-color", "blue"); 
}); 
$('.buttons').mouseleave(function() { 
    $(this).css("background-color", "red"); 
}); 

둘째, 특정 버튼은 3 색 (노란색)에있는 버튼을 변경하여 "클릭"되어 있음을 보여준다. 새로운/다른 버튼을 클릭 할 때까지 버튼을 노란색으로 유지하고 싶습니다. 그런 경우 새로 클릭 한 버튼을 노란색으로 변경하고 다른 모든 버튼을 원래 색상 (빨간색)으로 되돌리려합니다.

$(".buttons").click(function() { 
$(".buttons").css("background-color", "red"); 
$(this).css("background-color", "yellow"); 
}); 

이 버튼은 마우스가 클릭 된 버튼을 떠나 다른 것으로 이동할 때까지 잘 작동합니다. 이 경우 mouseleave는 노란색 버튼을 다시 빨간색으로 변경합니다.

jQuery 명령의 우선 순위를 매기는 방법이 있습니까? 대신 사용해야하는 또 다른 기능이 있습니까? 미리 감사드립니다.

+0

CSS로이 작업을 수행 할 수없고 클릭 이벤트에 노란색을 변경하는 클래스를 추가하는 이유가 있습니까? – Ballbin

답변

1

.css() 대신 클래스를 사용해야합니다. 훨씬 더 간단합니다. 그 CSS로

$('.buttons').hover(function(){ 
    $(this).toggleClass('hover'); 
}).on('click', function(){ 
    $('.buttons').removeClass('click').filter(this).addClass('click'); 
}) 

: 이런 식으로 뭔가를 사용

.buttons{ 
    background-color : red; 
} 

/* 
Could also be .buttons:hover an then remove the JS 
Much more efficient 
*/ 
.buttons.hover{ 
    background-color : blue; 
} 

.buttons.click{ 
    background-color : yellow; 
} 

바이올린 : http://jsfiddle.net/Re9bj/12/

+0

도움을 주셔서 감사합니다! 단점은 새 버튼을 클릭해도 클릭 된 버튼이 노란색으로 유지된다는 것입니다. 내가 최근에 클릭 한 버튼 만 노란색으로 유지하고 싶습니다. – katestrykermcm

+0

질문에서 그 지점을 놓치지 않았습니다. –

+0

잘 작동합니다. 감사! – katestrykermcm

0

가 클릭 된 버튼 ID를 제공하고

을 heres하는 MouseLeave에 jsfiddle을 해당 ID를 확인

$('.buttons').mouseenter(function() { 
    $(this).css("background-color", "blue"); 
}); 
$('.buttons').mouseleave(function() { 
    if ($(this).attr("id") == "clicked") { 
     $(this).css("background-color", "yellow"); 
    } else { 
     $(this).css("background-color", "red"); 
    } 
}); 

$(".buttons").click(function() { 
    $(".buttons").css("background-color", "red"); 
    $(".buttons").attr("id",""); 
    $(this).css("background-color", "yellow"); 
    $(this).attr("id","clicked"); 
}); 
+0

고마워요! jQuery로 가능한 것에 대해 더 자세히 알게되어 기쁩니다. 그러나 나는 다른 사람들의 의견 덕분에보다 효율적으로 CSS로 바꿀 생각입니다. – katestrykermcm

+0

@ user3064186 걱정하지 마세요 :) –

1

나는 이것을 달성하기 위해 CSS 클래스를 사용하도록 제안합니다.

Working example

CSS :

.buttons { 
    background-color: red; 
} 
.buttons:hover { 
    background-color: blue; 
} 
.clicked { 
background-color: yellow !important; 
} 

자바 스크립트 :

var $buttons = $('.buttons') 
$buttons.click(function() { 
    $buttons.removeClass('clicked'); 
    $(this).addClass('clicked'); 
}); 

HTML :

<button class='buttons'>Button 1 </button> 
<button class='buttons'>Button 2 </button> 
<button class='buttons'>Button 3 </button> 
<button class='buttons'>Button 4 </button> 
관련 문제