如何解决jQuery在锚标签上设置当前类
| 我目前有这个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\');
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。