2013-09-16 3 views
-3

다음 코드는 이벤트가 발생했을 때 요소에있는 텍스트 값에 따라 클릭시 특정 요소의 텍스트를 변경합니다.Click on Click 이벤트 최적화하기

http://jsfiddle.net/TNDhL/

$('#left').on('click', function(){ 
if ($("#textContainer:contains('something')").length) { 
    $('#textContainer').text('third text replacement'); 
    $('.elsewhere').text('more here'); 
} 
else if ($("#textContainer:contains('third text replacement')").length) { 
    $('#textContainer').text('now the next item'); 
    $('.elsewhere').text('something new here'); 
} 
else if ($("#textContainer:contains('now the next item')").length) { 
    $('#textContainer').text('new text here'); 
    $('.elsewhere').text('something else here'); 
} 
else if ($("#textContainer:contains('new text here')").length) { 
    $('#textContainer').text('something'); 
    $('.elsewhere').text('text here'); 
} 
}); 

$('#right').on('click', function(){ 
if ($("#textContainer:contains('something')").length) { 
    $('#textContainer').text('new text here'); 
    $('.elsewhere').text('something else here'); 
} 
else if ($("#textContainer:contains('new text here')").length) { 
    $('#textContainer').text('now the next item'); 
    $('.elsewhere').text('something new here'); 
} 
else if ($("#textContainer:contains('now the next item')").length) { 
    $('#textContainer').text('third text replacement'); 
    $('.elsewhere').text('more here'); 
} 
else if ($("#textContainer:contains('third text replacement')").length) { 
    $('#textContainer').text('something'); 
    $('.elsewhere').text('text here'); 
} 
}); 

버전을 작업을위한 위의 바이올린을 참조하십시오.

더 쉽게 확장 할 수 있도록이 기능을 더 쉽게 관리 할 수있는 방법을 찾고 싶습니다. 이 사건을 처리 할 수있는 더 좋은 방법이 있습니까? 이를 함수로 압축하고 변수를 사용하여 #textContainer의 값을 저장하는 것이 더 이상적입니다. 어떤 제안?

+0

나는'텍스트를 사용 http://codereview.stackexchange.com/ –

+0

에 게시하는 것이 좋습니다 것 -> replacements'지도 또는 간단한 배열을 저장하기 위해 모든 텍스트를 읽고 그것을 회전합니다. –

+0

이 질문은 http://codereview.stackexchange.com/ –

답변

1

간단한 카운터와 진행 상황을 추적 할 수있는 폐쇄를위한 완벽한 케이스처럼 보인다 .. 같은 것을 볼 수 있었다 :

var myTextRotator = (function() { 
    var myPhraseArray = ["first phrase", "second phrase"], 
     counter = 0; 
    return { 
     clickLeft: function() { 
      counter -= 1; 
      return myPhraseArray[counter]; //return array item or do your processing here 
     }, 
     clickRight: function() { 
      counter += 1; 
      return myPhraseArray[counter]; //return array item or do your processing here 
     } 
    }; 
}()); 

타이 jQuery를 .on()clickLeftclickRight 방법. 카운터가 0보다 작거나 배열 길이를 초과하지 않도록 조건을 추가해야 할 수 있습니다.

당신이이 같이 사용합니다 :

$(".left").on("click", function() { 
    myTextRotator.clickLeft(); 
}); 

$(".right").on("click", function() { 
    myTextRotator.clickRight(); 
});