<button type="button" onclick="func();">按钮</button>
var i = 0;
func(){
i += 1;
console.log(i)
}
Requirement: Click the button variable to increase by 1. Find the best way to achieve it.
To add, there are many ways to implement it.
Save directly into global variables - polluting the global namespace
Use a global array to save the global variables of the current app - does not conform to the current architecture
Closure - does not seem to adapt to the current scene (use onclick to trigger the function)
Docked into html elements - still very low
Using a large anonymous function to extend the life cycle of a variable - does not comply with the current architecture
某草草2017-06-26 11:00:14
Who said closures don’t apply?
var func = (function(){
var i = 0;
return function(){
i++;
console.log(i);
}
}());
Or you can do this:
var func = function(){
func.i++;
console.log(func.i);
};
func.i = 0;
PHP中文网2017-06-26 11:00:14
Saved in dom node attributes
<button data-click-number="0" type="button" id="incBtn" >按钮</button>
$("#incBtn").on('click',function(){
var preClickNumber=$(this).attr('data-click-number') ?: 1;
$(this).attr('data-click-number',preClickNumber++);
});
过去多啦不再A梦2017-06-26 11:00:14
js has no static variables. There are only local variables and global variables.
<button type="button" onclick="++i">按钮</button>
var i = 0;
黄舟2017-06-26 11:00:14
Closures are very popular. I suggest you read some books on functional expressions of JavaScript. This is also a major feature of JavaScript
let click = (() => {
var i = 0;
return function() {
i += 1;
console.log(i)
}
})()