-->

Bootstrap star-rating shown two times

2019-05-30 08:06发布

问题:

I am using this plugin to show star rating on my Bootstrap website. Here is part of the modal code in which I put the star rating (see the input element):

      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="userTitle"></h4>
        <input id="avg" class="rating" min=0 max=5 step=0.1 data-size="xs" data-readonly="true" data-show-clear="false" data-show-caption="false">
        <small id="tot_reviews"></small>
      </div>
      <div class="modal-body">

Here is the part of JS code in which I dynamically set the value of the stars:

$.getJSON("getData.php?rating=" + user.id, function(data) {
    if (data) {
        $.each(data, function(key, val) {
            var reviews = val.tot_reviews;

            $('#avg').rating('update', val.average);
            $("#tot_reviews").html("(" + reviews + " reviews)").html();
        });
    }
});

It seems to work well, in fact when I click on an item of the page I get this:

If I click again on the same item I get this:

I can't figure out why this happens.

回答1:

A few guidelines to check:

  • Note if you have set the input class=rating the plugin will be auto initialized without A NEED for javascript code on your side to initialize. This is mentioned in the usage section of the docs, the plugin features, and also with the first example on the basic usage section of the documentation.
  • Hence if you use your own javascript to initialize the plugin DO NOT set the class = rating, else you will have two parallel initializations causing undesirable effects.

In addition you may also note:

  • Ensure you have an unique ID for your HTML input element on the page. Duplicating the ID will have undesirable effects and break the star rating jquery plugin which uses the element ID to initialize. For example, if you have multiple ratings on the page <input id="avg"> should be unique with something like <input id="avg-1"> , <input id="avg-2"> and so on.
  • You have a loop in your code $.each... not sure what that does... but it is updating the rating. Ensure you are not in some way destroying an element with ajax rendered HTML and reinitializing another - duplicating the rating display.