javascript - js如何存儲(chǔ)每次點(diǎn)擊的索引值
問題描述
這個(gè)問題可能會(huì)比較弱,但我確實(shí)是沒找到好的方法去解決它,且周圍沒有其他前端可以問,先謝謝大家了...有這樣一個(gè)需求,dom如圖
一組button,我想記錄每次點(diǎn)擊的索引值,之前我是寫了一個(gè)cookie 來記錄...但是最近看了閉包和作用域之后感覺我的寫法多余了,應(yīng)該可以直接用返回值和函數(shù)解決
這樣直接打印肯定是空,因?yàn)辄c(diǎn)擊是異步的,沒有執(zhí)行肯定沒有賦值,但是這里如何去記錄每一次的值呢,如果是一個(gè)普通的函數(shù),執(zhí)行一次就是了,但是這個(gè)點(diǎn)擊也不能去單一的執(zhí)行,這里應(yīng)該如何存值呢?
問題解答
回答1:記憶函數(shù),記憶button索引值及點(diǎn)擊次數(shù),當(dāng)然也可以記憶歷史點(diǎn)擊索引序列
/* 記憶button索引值及點(diǎn)擊次數(shù)還有序列 */function memoizer() { let buttonIndexClickTimeHistory = {}; let buttonIndexClickQueueHistory = []; return function(idx) {if (typeof buttonIndexClickTimeHistory[idx] === ’number’) { buttonIndexClickTimeHistory[idx] ++;} else { buttonIndexClickTimeHistory[idx] = 1;}buttonIndexClickQueueHistory.push(idx);return { buttonIndexClickTimeHistory, buttonIndexClickQueueHistory}; };}const f = memoizer();$(’.button’).on(’click’, function() { console.log(f($(this).index()));});回答2:
把console.log(click_num);放在click函數(shù)中,這樣就能監(jiān)測每次點(diǎn)擊的賦值了
回答3:localstorage sessionstorage你可以試試
回答4:$(’.button’).click(function() { console.log($(this).index());});回答5:
index保存在一個(gè)變量中是比較合理的;想要每次打印index就把console.log()放在click事件中
相關(guān)文章:
1. python 利用subprocess庫調(diào)用mplayer時(shí)發(fā)生錯(cuò)誤2. python - pycharm 自動(dòng)刪除行尾空格3. python - Pycharm的Debug用不了4. python文檔怎么查看?5. datetime - Python如何獲取當(dāng)前時(shí)間6. javascript - 關(guān)于apply()與call()的問題7. html - eclipse 標(biāo)簽錯(cuò)誤8. 請問PHPstudy中的數(shù)據(jù)庫如何創(chuàng)建索引9. 安全性測試 - nodejs中如何防m(xù)ySQL注入10. javascript - nginx反向代理靜態(tài)資源403錯(cuò)誤?
