成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

javascript - js如何存儲每次點(diǎn)擊的索引值

瀏覽:124日期:2023-04-10 08:42:37

問題描述

這個問題可能會比較弱,但我確實(shí)是沒找到好的方法去解決它,且周圍沒有其他前端可以問,先謝謝大家了...有這樣一個需求,dom如圖javascript - js如何存儲每次點(diǎn)擊的索引值

一組button,我想記錄每次點(diǎn)擊的索引值,之前我是寫了一個cookie 來記錄...但是最近看了閉包和作用域之后感覺我的寫法多余了,應(yīng)該可以直接用返回值和函數(shù)解決javascript - js如何存儲每次點(diǎn)擊的索引值

這樣直接打印肯定是空,因為點(diǎn)擊是異步的,沒有執(zhí)行肯定沒有賦值,但是這里如何去記錄每一次的值呢,如果是一個普通的函數(shù),執(zhí)行一次就是了,但是這個點(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保存在一個變量中是比較合理的;想要每次打印index就把console.log()放在click事件中

標(biāo)簽: JavaScript
相關(guān)文章: