我有这个功能,我需要在函数外获取变量$ overall的值,我该怎么办?
$(function(){
function ca($tr_value, $qty ){
window.$overall = 0;
$($tr_value).each(function() {
var $qnt = $(this).find($qty);
var $price = $(this).find("td").eq(2);
var sum = parseFloat($price.text()) * parseFloat($qnt.val());
$(this).find("td").eq(3).text(sum);
$(this).find(".priceitem").attr('value', $(this).find("td").eq(2).text());
$(this).find(".totalitem").attr('value', sum);
$overall += sum;
return window.overall;
});
$("#total").text($overall);
$(".total").attr('value', $overall);
}
function ca_transp(){
var $overall_transp = 0;
$("tr.sum_transp").each(function() {
var $qnt = $(this).find(".qty_transp");
var $price = $(this).find("td").eq(2);
var sum = parseFloat($price.text()) * parseFloat($qnt.val());
$(this).find("td").eq(3).text(sum);
$(this).find(".priceitem").attr('value', $(this).find("td").eq(2).text());
$(this).find(".totalitem").attr('value', sum);
$overall_transp += sum;
});
$("#total_transp").text($overall_transp);
$(".total").attr('value', $overall_transp);
}
//]]>
function suma_total(){
var $suma_total = 0;
$("tr.total").each(function() {
//var $qnt = $(this).find(".total");
var $total_parcial = $(this).find("td").eq(1);
var sum = parseFloat($total_parcial.text());
$(this).find("td").eq(1).text(sum);
$suma_total += sum;
});
$("#total_cotizacion").text($suma_total);
$(".total_cotizacion").attr('value', $suma_total);
}
ca_transp();
$('input.qty_transp').bind('change keyup',function(){ca_transp();});
ca("tr.sum", ".qty");
$('input.qty').bind('change keyup',function(){ca("tr.sum", ".qty");});
alert($overall);
});
感谢您的帮助。
答案 0 :(得分:2)
在函数之外定义它,这将使它成为全局。
$(function(){
var $overall;
function ca($tr_value, $qty ){
$overall = 0;
$($tr_value).each(function() {
P.S你也在嵌套document.ready
个函数。你不需要这样做。事实上,你的代码可以清理很多。我认为您不需要创建全局$overall
变量。您的代码目前尚未正确构建,如果您明确表达了您的意图,那么我可以对其进行修改。
答案 1 :(得分:1)
这是一个简单的范围问题。
选项:强>
答案 2 :(得分:1)
您可以从ca函数返回evil global variable,而不是创建{{3}}。
$(function () {
//$overall doesn't need to be the same name here, you could call it "$returnedOverall" for example, and it would still work
var $overall = ca("tr.sum", ".qty");
alert($overall); //will show you the value of $overall, returned from the above call
$('input.qty').bind('change keyup', function () {
ca("tr.sum", ".qty");
var $overall2 = ca("tr.sum", ".qty");
alert($overall2); //will show you the value of $overall2, returned from the above call
});
});
//ca doesn't need to be in your jQuery document.ready function, it only needs to be called from within document.ready
function ca($tr_value, $qty) {
var $overall = 0;
$($tr_value).each(function () {
var $qnt = $(this).find($qty);
var $price = $(this).find("td").eq(2);
...
$overall += sum;
//don't return it here, this is inside your jQuery.each function
});
//return it here, from your ca function
return $overall;
}