使用jquery添加两个变量

Add two variable using jquery

本文关键字:两个 变量 jquery 添加 使用      更新时间:2023-09-26

朋友们,我有两个变量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;

你需要为这两个函数定义全局变量,比如

    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);
 });

将变量设置为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);
  });
});

用于外部访问变量。你必须声明变量(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;
 });
http://www.w3schools.com/js/js_scope.asp