2010-05-30 7 views
0

항목 목록이있는 간단한 페이지가 있습니다. 사용자가이 항목에 투표하도록 허용하고 있지만 사용자가 한 번만 투표하도록 허용하려고합니다. 목.jQuery 문제 도움말

if(!$(this).find(".item span").hasClass("voted")) { 
    $(".item").hover(function() { 
    $(this).find(".ratingbar").hide(); 
    $(this).find(".votebar").show(); 
    }, function() { 
    $(this).find(".votebar").hide(); 
    $(this).find(".ratingbar").show(); 
    }); 
}; 

이 같은 항목을 다시 투표에서 사용자를 방지 스크립트는 다음과 같습니다

나는 사용자가 투표 한 항목에 클래스를 추가하는 jQuery를 스크립트를했다.

$(".votebutton").click(function() { 
    $("div#"+offerid).find(".item").addClass("voted"); 
}); 

이것은 작동하지 않습니다. 항목을 가리키면 두 번째 스크립트가 html에 "투표 된"클래스를 성공적으로 추가 했더라도 호버 기능이 계속 실행됩니다.

왜 이럴 수 있습니까?

답변

7

당신은 .hover()는 DOM 요소에 부착하기 때문에,이를 방지하기 위해 .live() (또는 .delegate())를 사용합니다, 그것은 그 mousentermouseleave 이벤트 핸들러 바인딩을 해제하지 않는 클래스 변경 있다는 사실은 (이 가져가 실제에 결합하는 것입니다) . 이 같은 (이 이벤트 버블 링을 작동하기 때문에 셀렉터를 실행하기 전에 일치하는 경우가 확인되도록)를 가져, 그리고 당신이 원하는 것을 할 때 클래스 일치하는 경우

그러나, .live()는 평가 :

$(".item:not(.voted)").live('mouseenter', function() { 
    $(this).find(".ratingbar").hide(); 
    $(this).find(".votebar").show(); 
}).live('mouseleave', function() { 
    $(this).find(".votebar").hide(); 
    $(this).find(".ratingbar").show(); 
}); 

if 문을 수행 할 이유가 없습니다. 모든 요소에서 작동하며 한 번만 실행해야합니다. 이전에는 현재 항목에 voted 클래스가 있었는지 확인했지만 클래스가없는 각 요소에 대해 모두 .item (n 횟수) 개의 요소에 마우스를 올렸습니다 ... 대신이 작업을 한 번만 실행하십시오. 바깥에있는 루프는 바깥에서 직접 document.ready 핸들러에 있어야합니다.

편집 : 그냥 .toggle()를 사용하여 주변의 요소를 전환하고 있기 때문에 당신은 조금 더 간단/더 간결하고, 같은 효과입니다뿐만 아니라이 단축 될 수 있습니다 : 당신은 추가

$(".item:not(.voted)").live('mouseenter mouseleave', function() { 
    $(".ratingbar, .votebar", this).toggle(); 
}); 
+0

대단히 고마워요! jQuery 1.4로 업그레이드 한 후, 이것은 완벽하게 작동했습니다 :-) –

1

코드 뒤에 voted 클래스가 있지만 .hover()mouseentermouseleave 이벤트를 이미 .item에 바인딩했습니다.

당신은 당신의 정지에 계속 요소가 voted 클래스가있는 경우, 당신은 클래스를 확인하고 이벤트 핸들러에서 초기에 반환 할 수 있습니다에서 이벤트 핸들러하려면 다음을 투표 후

$(".item").hover(function() { 
    // save this variable so we don't need to call $() three times 
    var $this = $(this); 
    // stop processing the event if the item has the 'voted' class 
    if ($this.is('.voted')) return; 

    $this.find(".ratingbar").hide(); 
    $this.find(".votebar").show(); 
}, function() { 
    var $this = $(this); 
    // note - you might still want to process this event as they mouse out after voting? 
    if ($this.is('.voted')) return; 

    $this.find(".votebar").hide(); 
    $this.find(".ratingbar").show(); 
}); 

또는을 이벤트 처리기를 제거 할 수 있습니다.

$(".votebutton").click(function() { 
    $("div#"+offerid).find(".item").addClass("voted").unbind('mouseenter mouseleave'); 
});