问题描述
|
我目前有这个jquery代码来设置当前类,我是jquery的新手,并且想知道如何使它更简洁,更紧凑。目前可以使用,但是我想知道如何做得更好。
// add class current
$(\'.textResizing ul .normal a\').click(function () {
$(\'.textResizing ul .normal a\').addClass(\'current\');
$(\'.textResizing ul .medium a\').removeClass(\'current\');
$(\'.textResizing ul .large a\').removeClass(\'current\');
});
$ (\'.textResizing ul .medium a\').click(function () {
$(\'.textResizing ul .medium a\').addClass(\'current\');
$(\'.textResizing ul .normal a\').removeClass(\'current\');
$(\'.textResizing ul .large a\').removeClass(\'current\');
});
$ (\'.textResizing ul .large a\').click(function () {
$(\'.textResizing ul .large a\').addClass(\'current\');
$(\'.textResizing ul .normal a\').removeClass(\'current\');
$(\'.textResizing ul .medium a\').removeClass(\'current\');
});
解决方法
不知道您的html是什么样子,但是像这样? :
$(\'.textResizing ul a\').click(function () {
$(\'.textResizing ul a\').removeClass(\'current\');
$(this).addClass(\'current\');
});
,好吧,您可以缓存所有选择器。这是jq中最简单,最有用的优化,因为每次使用seletors时,jq都需要解析dom来查找元素。所以:
// add class current
var na = $(\'.textResizing ul .normal a\'),ma = $(\'.textResizing ul .medium a\'),la = $(\'.textResizing ul .large a\');
na.click(function () {
this.addClass(\'current\');
ma.removeClass(\'current\');
la.removeClass(\'current\');
});
ma.click(function () {
this.addClass(\'current\');
na.removeClass(\'current\');
la.removeClass(\'current\');
});
la.click(function () {
this.addClass(\'current\');
na.removeClass(\'current\');
ma.removeClass(\'current\');
});