朋友们,我有两个变量price1&价格2,我正在使用onchange事件动态获取价格值现在我想添加这两个变量。
//get support layer firmness price
$('.support-layer-firmness').on('change', function(e) {
//first price
var price1 = 300;
});
$('.support-layer-thickness').on('change', function(e) {
//second price
var price2 = 200;
});
Now I want to add both variables price1 & price2
eg price = price1+price2;
o/p price= 500;
我怎样才能实现这一目标..
答案 0 :(得分:1)
将变量设为global
并在各个更改事件中设置值,然后您可以将值添加到任何位置。
$(document).ready(function(){
var price1=0;
var price2=0;
$('.support-layer-firmness').on('change', function(e) {
//first price
price1 = 300;
});
$('.support-layer-thickness').on('change', function(e) {
//second price
price2 = 200;
alert(price1 + price2); //add price
});
//or you can calculate them on button click
$('#btnAdd').click(function(){
alert(price1 + price2);
});
});
答案 1 :(得分:1)
你需要为这两个函数定义全局变量,比如
var price=0,price1=0,price2=0;
//get support layer firmness price
$('.support-layer-firmness').on('change', function(e) {
//first price
price1 = 300;
price=price1+price2;
alert(price);
});
$('.support-layer-thickness').on('change', function(e) {
//second price
price2 = 200;
price=price1+price2;
alert(price);
});
答案 2 :(得分:0)
从外面访问变量。您必须在事件句柄之外声明变量(price1& price2)。
var price1,price2; //<= declare here
//get support layer firmness price
$('.support-layer-firmness').on('change', function(e) {
//first price
price1 = 300;
});
$('.support-layer-thickness').on('change', function(e) {
//second price
price2 = 200;
});