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?
给我你的怀抱2017-07-05 10:40:25
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()));
});
黄舟2017-07-05 10:40:25
Put console.log(click_num);
in the click
function, so that you can monitor the value assigned to each click
PHP中文网2017-07-05 10:40:25
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