how to control target in a multiple jquery raty sy

2019-07-29 07:18发布

I'm using jquery raty to do a rating page in php, where multiple rating are displayed. It works ok unless one thing. The score function, and the click function works ok. But I'm having problems trying to set the target for each element. What I want is to show the rating choice on hover over each star. It should show the hint in the div with class "star_hint", but it isn't.

Each element is displayed in a div like this:

<div class="span4">
   <h4>First valoration</h4>
   <div class="star" data-number="3"></div>                                         
   <input type="hidden" class="score_value" />                                  
   <div class="star_hint"></div>
</div>

<div class="span4">
   <h4>Second valoration</h4>
   <div class="star" data-number="4"></div>                                         
   <input type="hidden" class="score_value" />                                  
   <div class="star_hint"></div>
</div>
etc....

And the script is this one:

$('.star').raty({
    target: $(this).next('.star_hint'),
    score: function() {
        return $(this).attr('data-number');  // set default value 
    },
    click: function(score) {
        $(this).next().val(score);  // save clicked value in hidden input
        GetAverageNote();  // calculates average note from all ratys
    }
});

I can not use an id for target, because each star item has a different target. I tried also return the value within a function, like score and click does, but it doesn't worked. Like that:

target: function() {
    $(this).next('.star_hint');
   }

Anyone have an idea on how to make this work?

2条回答
虎瘦雄心在
2楼-- · 2019-07-29 07:42

You can loop thru all the span or divs for which raty() method needs to be bound and then pass tid as a variable to set raty({target:tid})

Rate <span id="star_xxx" data-number="3" rel="#hint_xxx" ></span>  <span  id="hint_xxx">   </span>

$( document ).ready(function() {
$('span[id^="star"]').each(function(){
    var tid = $(this).attr('rel'); 
    $(this).raty({
        target : tid ,
        starOff : '/img/star-off.png', 
        starOn : '/img/star-on.png'     

}) 
}) 


});
查看更多
仙女界的扛把子
3楼-- · 2019-07-29 07:54

html

<div class="star" data-score="2.6"></div><span class="hint"></span> 

js

$(function () {
     $('div[class^="star"]').each(function(){
        $(this).raty({
            readOnly:true,
            score: function() {return $(this).attr('data-score');},
            }) 
            $(this).next().text($(this).attr('data-score'));
        });
    });
查看更多
登录 后发表回答