一個很好的技術,因爲這是一個自動執行的閉合:
// bob is a global variable, which you want to avoid
var bob = 1;
// By wrapping this function declaration in parentheses, then
// appending(), it gets invoked immediately. But everything
// inside it is scoped to the anonymous function!
(function() {
// sue can only be seen inside this function
var sue = 1;
// But if you want to, you can still create global variables.
// This creates a global variable called joe:
window.joe = 1;
})();
將這種技術應用到你的代碼中,你可以寫這個沒有全局變量:
(function() {
var size_li = $("#myList li").size();
var x = 3;
$('#myList li:lt(' + x + ')').show();
$('.loadmore').on('click', function() {
x = (x + 2 <= size_li) ? x + 2 : size_li;
$('#myList li:lt(' + x + ')').show();
});
})();
這不是你問的,所以我不會在我的答案中包含它,但行'x =(x + 2 <= size_li)? x + 2:size_li;'可以簡化爲'x = Math.min(x + 2,size_li);' – AmericanUmlaut