使用JQuery更改li元素的类

4
我有一个导航,通过使用类active来突出显示当前选定的导航点。当用户访问新的导航点时,我想切换“旧”选定的导航点,并将新导航点的li元素的类切换为“active”。
我遇到了jquery部分的问题,它只应该更改旧元素的li类的切换状态,并将类添加到单击的li元素中。这可能是标准情况,但我不知道一个好的和简单的解决方案。
示例(点击之前):
<ul class="x-navigation">
<li class="active">
    <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard</span></a>                        
</li>
<li>
    <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard2</span></a>                        
</li>
</ul>

结果(点击“Dashboard2”后):

<ul class="x-navigation">
<li>
   <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard</span></a>                        
</li>
<li class="active">
  <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard2</span></a>                        
</li>
</ul>

我的尝试

$(".x-navigation li").on("click", "a", function(){
        event.preventDefault();
        //alert("test");

        ($this).parent().removeClass("active");
        ($this).addClass("active");

        //alert($this.child().href);
});

错误描述:
Uncaught ReferenceError: $this is not defined at this row: "($this).parent().removeClass("active");

"我希望 $this 是被点击的 li 元素,这是一个常见问题,希望你们能够帮助我。"

终于有一个符合 SO 所有规则的问题了... - Ian Hazzard
2个回答

5
< p > $ 符号位于括号外部。美元符号是您提供给 jQuery 构造函数调用的参数 this

$(this).parent()

以及其他。


2
你的问题告诉我你想要切换新导航点的li元素的类名为"active",这意味着你希望在刚刚点击的链接的li元素上放置"class active"。
但是你此处正在做的是:
($this).addClass("active");

因此,您需要将类“active”添加到锚点元素中。
$(".x-navigation li").on("click", "a", function(){

also this part :

($this).parent().removeClass("active");

应该这样写,将$放在(this)外面:
$(this).parent().removeClass("active");

现在,如果您真的想要切换它,您可以简单地执行以下操作:
$(".x-navigation li").on("click", "a", function(){
  event.preventDefault();
  $(this).parent().addClass("active").siblings().removeClass("active");
});

但它停止了加载我的PHP页面(在href中)。 - Chamal
event.preventDefault();可以阻止默认的href行为,只执行函数内部的内容。 - Ashenvale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接