在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ js點擊事件里面有個循環(huán)我可以點擊一次執(zhí)行一次循環(huán)嗎

js點擊事件里面有個循環(huán)我可以點擊一次執(zhí)行一次循環(huán)嗎

let arr = [

                {id:1,text:"生活不只眼前的茍且"},
                {id:2,text:"還有詩"},
                {id:3,text:"和遠方"}
                ];

let items = [];
$("#add").click(function(){
for(var i = 0;i<arr.length;i++){

    items.push(arr[i]); 
 }  

})
//這樣寫會直接把arr所有的數(shù)據(jù)全部加進去,希望是點擊一次 添加arr中的一個id

回答
編輯回答
離殤

可以先確定這個id,然后做一個比較
var id = ''

$("#add").click(function(){
    for(var i = 0;i<arr.length;i++){
        if (id === arr[i].id) {
            items.push(arr[i]); 
        }
    }  
})
2018年2月15日 21:03
編輯回答
吃藕丑

閉包+立即執(zhí)行函數(shù)實現(xiàn):

$('#add').click(
    (function() {
        let count = 0;
        return function() {
            items.push(arr[count++]);
        };
    })()
);
2018年1月2日 19:01
編輯回答
冷咖啡
  // 這里定義一個全局的index標識上次添加的id的位置
  let index = 0;
  let arr = [
    {id:1,text:"生活不只眼前的茍且"},
    {id:2,text:"還有詩"},
    {id:3,text:"和遠方"}
  ];
  let arrLength = arr.length;
  let items = [];
  document.getElementById("add").onclick = function(){
    // 防止數(shù)組下標溢出
    if (index <= arrLength - 1) {
      items.push(arr[index]);
      // 添加完成之后下標后移
      index++;
    }
    console.log(items);
  }
2017年11月17日 19:55