2016-09-27 81 views
-2

我已经为价目表放了一些单选按钮。 我写了这个:如何访问jQuery中的函数内的变量?

$(document).ready(function() { 
    $('#windowsRange input').on('change', function() { 
     var windowPrice = $('input[name=windowName]:checked', '#windowsRange').val(); 
    }); 
    $('#profilesRange input').on('change', function() { 
     var profilePrice = $('input[name=profileName]:checked', '#profilesRange').val(); 
    }); 
    $('#tapesRange input').on('change', function() { 
     var tapePrice = $('input[name=tapeName]:checked', '#tapesRange').val(); 
    });  
    $('.totalPrice').html(windowPrice + profilePrice + tapePrice); 
}); 

我可以访问内部对这些方法的变量,但我想加上所有这些&的提出,在.totalPrice类... 没有办法做到这一点? 谢谢...

+0

在on函数之外初始化它们,然后你可以在文档准备好的任何地方访问它们 – depperm

+1

这种方法根本不会做你认为它的作用。 –

+0

@ssube它没有任何问题&它不显示任何错误我的朋友,我只想访问变量... –

回答

4

你可以简单地让 “全球” 瓦尔

$(document).ready(function() { 
    var windowPrice, profilePrice, tapePrice; 
    $('#windowsRange input').on('change', function() { 
     windowPrice = parseInt($('input[name=windowName]:checked', '#windowsRange').val()); 
     setTotal(); 
    }); 
    $('#profilesRange input').on('change', function() { 
     profilePrice = parseInt($('input[name=profileName]:checked', '#profilesRange').val()); 
     setTotal(); 
    }); 
    $('#tapesRange input').on('change', function() { 
     tapePrice = parseInt($('input[name=tapeName]:checked', '#tapesRange').val()); 
     setTotal(); 
    }); 
    function setTotal() {  
     $('.totalPrice').html(windowPrice + profilePrice + tapePrice); 
    } 
    setTotal(); 
}); 
+0

谢谢,它的作品,但它不加上它们,它显示彼此相邻... –

+0

你不需要setTotal每次输入变化? @AliBahaari – Davide

+1

注意输入值是字符串,您需要将它们转换为数字 –

2

花点时间准备:

Decoupling Your HTML, CSS, and JavaScript

所以,如果我做到了,那就是:

$(document).ready(function() { 
    var totalPriceElements = '.js-adjust-total-price'; 

    $(totalPriceElements).on('change', function() { 
     var totalPrice = 0; 
     $(totalPriceElements).each(function(i, element){ 
      totalPrice += $(element).val(); 
     }) 
     $('.totalPrice').html(totalPrice); 
    }); 
}); 

现在不是所有高度耦合的元素(使用ID和元素标签名称),您可以将该类应用于调整总价格的元素。任何更改Ids或输入类型的人都不会破坏JavaScript。

+0

谢谢埃里克... –