我正在使用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/