2013-06-26 3 views
1

У меня есть следующая функция jQuery, которая помогает мне со звездным рейтингом/голосованием. Он отлично работает, и я привел пример из учебника. Когда пользователь выбирает звезду, числовое значение хранится на стороне сервера, а затем, если они вернутся к ней, количество звезд будет «желтым», а не «серым». Это только ошибка, когда вы возвращаетесь к ней после голосования и начинаете парить над звездами, ваши первоначальные звезды, которые вы выбрали, не остаются «желтыми», но становятся серыми.jQuery Star-Based Voting Managing State

Вот мой код, и я извиняюсь за его долговечность:

 (function ($) { 
      $.fn.starFunction = function (stars, initialRating) { 
       //Save the jQuery object for later use. 
       var elements = this; 

       //Go through each object in the selector and create a ratings control. 
       return this.each(function() { 

        //Make sure intialRating is set. 

        if (!initialRating) 
         initialRating = 0; 

        //Save the current element for later use. 
        var containerElement = this; 

        //grab the jQuery object for the current container div 
        var container = jQuery(this); 

        //Create an array of stars so they can be referenced again. 
        var starsCollection = Array(); 

        //Save the initial rating. 
        containerElement.rating = initialRating; 

        //Set the container div's overflow to auto. This ensure it will      grow to 
        //hold all of its children. 
        container.css('overflow', 'auto'); 

        //create each star 
        for (var starIdx = 0; starIdx < stars; starIdx++) { 

         //Create a div to hold the star. 
         var starElement = document.createElement('div'); 

         //Get a jQuery object for this star. 
         var star = jQuery(starElement); 

         //Store the rating that represents this star. 
         starElement.rating = starIdx + 1; 

         //Add the style. 
         star.addClass('jquery-ratings-star'); 

         //Add the full css class if the star is beneath the initial rating. 
         if (starIdx < initialRating) { 
          star.addClass('jquery-ratings-full'); 
         } 

         //add the star to the container 
         container.append(star); 
         starsCollection.push(star); 

         //hook up the click event 
         star.click(function() { 
          //When clicked, fire the 'ratingchanged' event handler. Pass the rating through as the data argument. 
          elements.triggerHandler("ratingchanged", { rating: this.rating }); 
          containerElement.rating = this.rating; 
         }); 

         star.mouseenter(function() { 
          //Highlight selected stars. 
          for (var index = 0; index < this.rating; index++) { 
           starsCollection[index].addClass('jquery-ratings-full'); 
          } 
          //Unhighlight unselected stars. 
          for (var index = this.rating; index < stars; index++) { 
           starsCollection[index].removeClass('jquery-ratings-full'); 
          } 
         }); 

         container.mouseleave(function() { 
          //Highlight selected stars. 
          for (var index = 0; index < containerElement.rating; index++) { 
           starsCollection[index].addClass('jquery-ratings-full'); 
          } 
          //Unhighlight unselected stars. 
          for (var index = containerElement.rating; index < stars ; index++) { 
           starsCollection[index].removeClass('jquery-ratings-full'); 
          } 
         }); 
        } 
       }); 
      }; 
     })(jQuery); 
+0

Какой плагин ты используешь? Если это одно: http://www.fyneworks.com/jquery/star-rating/ Затем вы также должны предоставить нам HTML-код, который вы используете. –

+0

нет, это не тот, хотя выглядит перспективным – Matt

ответ

1

Вы можете использовать:

star.unbind('mouseenter'); 
star.unbind('mouseleave'); 

В вашем случае щелчка или даже:

$('.jquery-ratings-star').unbind('mouseenter'); 
$('.jquery-ratings-star').unbind('mouseleave'); 

http://api.jquery.com/unbind/

+0

, который отлично работает, пока пользователь остается на странице. Если они уйдут и вернутся и начнут парить над изображениями, они все снова сеют. Похоже, вы на что-то. – Matt