javascript - jquery从另一个函数获取变量

标签 javascript jquery

我正在使用jqueryraty评级插件,并且想获取点击时的分数并将其传递给第二个函数,该函数将通过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
    });
 }

}); });

最佳答案

在变量前加上 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(如果“cancel”是单击)。因此,与 null 的比较对于未选择值的用户或清除该值的用户(如果启用了该设置)都有效。

关于javascript - jquery从另一个函数获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22900361/

相关文章:

JavaScript 和 php 一段时间后停止工作,只有在重命名一些变量时才有效

javascript - 在 javascript 中迭代项目的最佳方法是什么?

javascript - 像 Sass 这样的 jquery 插件

javascript - jQuery .val() 没有选取innerText 的值

javascript - Google Material 折线图 - 刻度

javascript - 从云功能中的父级获取数据?

javascript - 在用户单击按钮时调用 GreaseMonkey 函数

jquery - 使用 jQuery 的字体大小在 iPhone 上不起作用

javascript - 结合 eq、parent 和 index 似乎不起作用

jquery - 如何在 CakePHP 表单的日期时间字段中允许 null?