2013-03-26 28 views
1

我使用jquery raty plugin,有click event裏面我是用送的評價數據,然後從數據庫返回新的評級,但我不能想出如何更新返回的評價,我的代碼:如何更新RATY值

$('.starrating').raty({ 
      number:10, 
      score: function() { 
        return $(this).attr('data-rating'); 
       }, 
      click: function(score, evt) { 
       var contentid = $(this).attr('id'); 
       $.post('/main/rating.php',{score:score, contentid:contentid }, 
         function(data){ 
          //alert(data+' Score = '+score); 
          $(this).data('rating',2); 
       }); 
      } 
      }); 

我嘗試了下面但沒有成功;

$(this).data('rating',2); 

感謝您的任何幫助。

+0

通過設置'$ .fn.data'你只設置jQuery的數據緩存鏈接元素。甚至沒有真正的數據屬性 – 2013-03-26 13:58:25

回答

2

根據RATY文檔

附:嘗試$(this).raty({ score: 2 });如果你還需要設置數據屬性,你可以試試這個:$(this).raty({ score: 2 }).attr('data-rating', 2);

P.P.S.基於你對你的參數被重置意見的權利處理多元素

$('.starrating').raty({ 
    number:10, 
    score: function() { 
     return $(this).attr('data-rating'); 
    }, 
    click: function(score, evt) { 
     var target = $(this), 
      contentid = target.attr('id'); 

     $.post('/main/rating.php',{score:score, contentid:contentid }, 
      function(data){ 
       target 
        .raty({ 
         score: data.score 
        }) 
        .attr('data-rating', data.score); 
      }); 
     } 
    }); 
+0

我已經有了,我必須動態更新評級值。 – user969068 2013-03-26 15:22:04

+0

@dshah你應該把這段代碼放在'$ .post'回調中 – 2013-03-26 15:39:04

+0

嗯謝謝它可以工作,但不是用$(this)但是元素名稱爲$('。starrating'),並且我必須重新添加所有參數.raty({params})在callabck中,它不是非常有效的方式,但由於沒有其他方式我可以找到,所以感謝它標誌着它的解決。 – user969068 2013-03-26 16:03:34

0

click事件更新,我在下面加了一些想法。

//SET RATY DEFAULTS 
     $.fn.raty.defaults.path = 'img'; 
     $.fn.raty.defaults.cancel = true; 
     //etc 

在您的成功功能中,使用新數據重置評分。只有指定的選項纔會被覆蓋。

$(this).raty('set', { option: value }); 

例如,更新得分

$(this).raty('set', { score: 2 }); 

如果您有this麻煩,試試下面的代碼(在此基礎上回答Passing variables through to AJAX

$.fn.raty.defaults.click= function(score, evt) 
{ 
    var target = $(this), 
    contentid = target.attr('id'); 
    postvalue(score,target, contentid); 
} 

function postvalue (score,target, contentid) 
{ 
    $.post('/main/rating.php',{score:score, contentid:contentid }, 
    function(data) 
    { 
     target.raty({score: data.score}).attr('data-rating', data.score); 
    }); 
} 

注:無此代碼已經過測試。

0

遇到了一些麻煩這個,這個工作對我來說:

$('.rating').raty('score', score);