jquery从另一个函数获取变量

时间:2014-04-06 21:38:28

标签: javascript jquery

我正在使用jquery raty评级插件,并想在点击时获取分数并将其传递给第二个函数,该函数将通过ajax将其发送到php以插入数据库以及反馈。有人可以帮帮我吗?

 $(function() {
    $('.rate').raty({
    click: function(score, evt) {
    var rate = score;//this is the variable I want to pass
    },
    path     : '../img',
     size     : 24,
     half :true,
    cancel      : true,
    cancelOff : 'cancel-off-big.png',
    cancelOn  : 'cancel-on-big.png',
    starHalf : 'star-half-big.png',
    starOff  : 'star-off-big.png',
    starOn   : 'star-on-big.png',
    starOn   : 'star-on-big.png',
     score: function() {
    return $(this).attr('data-score');
    }
  });

  //the below function is in included js file
 $(function() {
$("#submit" ).click(function() {
   //how can I access the above var here? 
   if(rate == "")
{
    $(".error").html("Score is missing");
    }
    else{


$.ajax({
    //send data
    });
 }

});   });

2 个答案:

答案 0 :(得分:2)

使用var前缀变量使其仅在该范围内可访问。通过这样做,您只能在.rate的点击处理程序中使其可用。

相反,要扩大范围;

// define here, in a scope both functions can access!
var rate = null;

$(function () {
    $('.rate').raty({
        click: function (score, evt) {
            rate = score;
        },
        path: '../img',
        size: 24,
        half: true,
        cancel: true,
        cancelOff: 'cancel-off-big.png',
        cancelOn: 'cancel-on-big.png',
        starHalf: 'star-half-big.png',
        starOff: 'star-off-big.png',
        starOn: 'star-on-big.png',
        starOn: 'star-on-big.png',
        score: function () {
            return $(this).attr('data-score');
        }
    });

    //the below function is in included js file
    $(function () {
        $("#submit").click(function () {
            if (rate == null) {
                $(".error").html("Score is missing");
            } else {

            $.ajax({
                //send data
            });
        }
    });
});

您注意到我已将您的rate == ""更改为rate == null;我查看了raty文档,我可以为click处理程序找到的唯一有效值是数字或null(在事件"取消"点击)。因此,与null的比较将适用于未选择值的用户或清除值的用户(如果启用了该设置)。

答案 1 :(得分:0)

可变速率在回调函数中定义。如果它在函数内部定义,则表示它是局部变量,并且它是有效的并且仅存在于此函数中。您必须从此函数中定义此变量。

如果你不能这样做 - 因为你无法编辑的jQuery Raty代码的外部文件 - 所以在这种情况下 - 我认为唯一的一种可能性是读取DOM并获取生成的隐藏输入的值作者:jQuery Raty。

Raty code

但是当以编程方式更改值时,输入不会触发更改事件,因此我不知道如何检测该用户点击的评级图标.......

相关问题