2014-01-09 3 views
0

탐색 모음을 만들고 작동시키고 있습니다. 그러나 나는 내 글을 바꾸고 싶다. 다음과 같습니다 반복적 인 코드가있다 :자바 스크립트, 이것을 루프로 변경할 수 있습니까?

$("nav span").mouseover(function(){ 
var currentColor = $("#" +$(this).attr("data-loc")).css("backgroundColor"); 
var currentPos = $(this).position().left; 

if ($(this).attr("data-loc") === "home"){ 
    $("#hoverstyle").animate({"left":currentPos},150); 
    $("#hoverstyle").css("backgroundColor",currentColor); 
    $("#hoverstyle").css({width:$(this).width()}); 

} 
else if($(this).attr("data-loc") === "writer"){ 
    $("#hoverstyle").animate({"left":currentPos},150); 
    $("#hoverstyle").css("backgroundColor",currentColor); 
    $("#hoverstyle").css({width:$(this).width()}); 
} 
else if($(this).attr("data-loc") === "historian"){ 
    $("#hoverstyle").animate({"left":currentPos},150); 
    $("#hoverstyle").css("backgroundColor",currentColor); 
    $("#hoverstyle").css({width:$(this).width()}); 

} 
else if($(this).attr("data-loc") === "teacher"){ 
    $("#hoverstyle").animate({"left":currentPos},150); 
    $("#hoverstyle").css("backgroundColor",currentColor); 
    $("#hoverstyle").css({width:$(this).width()}); 

} 
else if($(this).attr("data-loc") === "fencing"){ 
    $("#hoverstyle").animate({"left":currentPos},150); 
    $("#hoverstyle").css("backgroundColor",currentColor); 
    $("#hoverstyle").css({width:$(this).width()}); 

} 
}); 

하지만 그것은 더 나은 내가 루프 만들기로 생각하는 방법을 알아낼 수 없습니다,하지만 난 -.- 그것을 알아낼 수 없습니다. . 도와주세요!

+1

왜 '스위치'를 사용하지 않습니까? – Cilan

+3

왜'if' /'else if'를 사용하고 있습니까? 모든 상황에서 똑같은 일을하고있는 것입니다. –

+1

왜 다른 사람을 추가했을 때 그들에 별도의 아무것도하지 않을 때 –

답변

8

유효한 로캘 값의 배열을 만든 다음 해당 요소의 배열에 값이 있는지 확인합니다. 이 배열에서 발견 된 경우

var locs = ['home', 'writer', 'historian', 'teacher', 'fencing']; 

var thisLoc = $(this).attr('data-loc'); 
if (locs.indexOf(thisLoc) > -1) { 
    //do stuff 
} 

배열의 indexOf 방법은 항목의 인덱스를 반환합니다. 그렇지 않으면 -1을 반환합니다. 따라서 -1 이상이라면 data-loc 값이 배열에 있다는 것을 알고 있으므로 조치를 취할 수 있습니다.


는 당신은 $('#hoverstyle') 개체를 재사용하여 jQuery를 조작 정리도 할 수있는, 이것은 체인이라고합니다. jQuery의 메서드는 대개 jQuery 객체를 반환하므로 객체를 다시 찾지 않고 호출을 연결할 수 있습니다. 그리고 css() 호출을 두 속성을 가진 객체를 전달하는 하나의 호출로 결합 할 수 있습니다.

$("#hoverstyle") 
    .animate({"left":currentPos},150) 
    .css({ 
     backgroundColor: currentColor, 
     width:$(this).width() 
    }); 
+0

** + 1 ** 아주 좋은 생각입니다. 그리고 다음번 편집에서 실제로 * 설명 된 이유는 무엇입니까? – Cilan

+1

'Array.prototype .indexOf'는 IE <= 8에서 지원되지 않습니다. –

+0

IE <= 8을 지원해야하는 경우 polyfill : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill –

3

Switch?

switch ($(this).attr("data-loc")) 
{ 
    case "home": 
    case "writer": 
    case "historian": 
    case "teacher": 
    case "fencing": 
     $("#hoverstyle").animate({"left":currentPos},150); 
     $("#hoverstyle").css("backgroundColor",currentColor); 
     $("#hoverstyle").css({width:$(this).width()}); 
     break; 
    default: 
     break; 
} 
+0

같은 요소를 세 번 선택할 필요가 없습니다. 왜 그 방법을 연결하지 않습니까? –

+0

** + 1 ** 답변으로 댓글을 게시하는 데 문제가 있습니다. 항상 잘못된 것 같습니다. P – Cilan

+0

동일하지만 평판이 좋지 않아서 댓글을 달 수는 없습니다./ – Yoann

관련 문제