How does js store the index value of each click
ringa_lee
ringa_lee 2017-07-05 10:38:25
0
5
731

This question may be weak, but I really haven't found a good way to solve it, and there are no other front-ends around to ask. Thank you all in advance...
There is such a need, the dom is shown in the picture

A set of buttons. I want to record the index value of each click. I wrote a cookie to record it before... But after recently looking at closures and scopes, I feel that my writing method is redundant. It should be able to be used directly. Return value and function solution

This direct printing will definitely be empty, because the click is asynchronous, and there will definitely be no assignment if it is not executed. But how to record the value of each time here? If it is an ordinary function, it can be executed once, but this click cannot For a single execution, how should the value be stored here?

ringa_lee
ringa_lee

ringa_lee

reply all(5)
给我你的怀抱

Memory function, remember button index value and number of clicks, of course, you can also remember the historical click index sequence

/* 记忆button索引值及点击次数还有序列 */
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()));
});
黄舟

Put console.log(click_num); in the click function, so that you can monitor the value assigned to each click

三叔

You can try localstorage sessionstorage

大家讲道理

$('.button').click(function() {
    console.log($(this).index());
});
洪涛

It is more reasonable to save index in a variable;
If you want to print index every time, put console.log() in the click event

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template