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\');
});
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...