js点击事件里面有个循环我可以点击一次执行一次循环吗

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所有的数据全部加进去,希望是点击一次 添加arr中的一个id


胡子哥哥
浏览 614回答 3
3回答

肥皂起泡泡

&nbsp; // 这里定义一个全局的index标识上次添加的id的位置&nbsp; let index = 0;&nbsp; let arr = [&nbsp; &nbsp; {id:1,text:"生活不只眼前的苟且"},&nbsp; &nbsp; {id:2,text:"还有诗"},&nbsp; &nbsp; {id:3,text:"和远方"}&nbsp; ];&nbsp; let arrLength = arr.length;&nbsp; let items = [];&nbsp; document.getElementById("add").onclick = function(){&nbsp; &nbsp; // 防止数组下标溢出&nbsp; &nbsp; if (index <= arrLength - 1) {&nbsp; &nbsp; &nbsp; items.push(arr[index]);&nbsp; &nbsp; &nbsp; // 添加完成之后下标后移&nbsp; &nbsp; &nbsp; index++;&nbsp; &nbsp; }&nbsp; &nbsp; console.log(items);&nbsp; }

当年话下

可以先确定这个id,然后做一个比较var id = ''$("#add").click(function(){&nbsp; &nbsp; for(var i = 0;i<arr.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; if (id === arr[i].id) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; items.push(arr[i]);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp;&nbsp;})

慕婉清6462132

闭包+立即执行函数实现:$('#add').click(&nbsp; &nbsp; (function() {&nbsp; &nbsp; &nbsp; &nbsp; let count = 0;&nbsp; &nbsp; &nbsp; &nbsp; return function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; items.push(arr[count++]);&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; })());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript