我想在paginate()
範圍內定義變量。然而,任何變量與this
定義(例如this.parentlist
)不可用了jQuery click
方法在javascript函數的範圍內定義一個變量的最佳方式是什麼?
var paginate = function(elt) {
//would like to define variables within scope of paginate()
//however, any variable defined with this (e.g. this.parentlist) is not available within the jQuery click method
this.parentlist = elt.find('ul');
var listitems = elt.find('li');
this.listcount = this.list.find('li').size();
var showitems = '3';
this.numberofpages = ~~((this.count/this.show) + 1);
this.parentlist.after('<ul class="links"></ul>');
for(i=1;i<=this.numberofpages;i++) {
$('.links').append('<li><a href="#'+i+'">'+i+'</a></li>')
};
//click a link
$('.links a').click(function() {
//this.parentlist is not available here
listitems.hide();
this.start = listitems.index() * showitems;
this.end = (this.start + 1) * showitems;
this.selected = listitems.slice(this.start,this.end).show().addClass('selected');
console.log(this.selected);
console.log(this.parentlist);
});
};
paginate($('.pages'));
-1`this`在給定的範圍是`window`對象。重複調用`paginate()`會導致問題。 – 2011-12-14 19:04:22
謝謝,更新。 – 2011-12-14 20:06:00