更新数组对象值

时间:2015-01-15 06:54:55

标签: javascript jquery

如何更新数组对象值,我的对象名totaldays的值为0。当我按下按钮时,值+1。点击"totaldays":0

,现在示例"totaldays":1

var checkin_status = [
{"startdate":"2015-01-08",
"totaldays":0,
"roadmap":[	
			
			{"gifttype":"stars","quantity":100,"day":1},
			{"gifttype":"stars","quantity":500,"day":3},
			{"gifttype":"stars","quantity":1000,"day":10},
			{"gifttype":"stars","quantity":1200,"day":20},
			{"gifttype":"stars","quantity":2200,"day":30},
			
		  ]

}];


clickforfun(checkin_status);

function clickforfun(){
      var button = "<input type='button' id='click_button' class='click_button' value='Click me now' />"
 
     $("#call_button").append(button);
 
     $("#click_button").click(function(){
         checkin_status[0].totaldays + 1;
     });
 console.log(checkin_status[0].totaldays); // now should be 1 ?
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="call_button"></div>

2 个答案:

答案 0 :(得分:0)

错误的点击事件声明并将checkin_status[0].totaldays + 1;更改为checkin_status[0].totaldays += 1;试试这个: -

 $("#click_button").click(function(){
     checkin_status[0].totaldays += 1;
     clickforfun(checkin_status);
 });

function clickforfun(){   
 console.log(checkin_status[0].totaldays); // now should be 1 ?
}

Demo

答案 1 :(得分:0)

重新分配值

$(".click_button").click(function(){
    checkin_status[0].totaldays += 1; // +=, not just +
});

这是

的简写
$(".click_button").click(function(){
    checkin_status[0].totaldays = checkin_status[0].totaldays + 1; // +=, not just +
});