jQuery删除活动类并将其添加到li节点& preventDefault问题 [英] Jquery removing and adding active class to li nodes & issues with preventDefault

查看:57
本文介绍了jQuery删除活动类并将其添加到li节点& preventDefault问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery删除和&在LI导航上添加活动"类可以使用preventDefault,但不再需要链接

Jquery Removing & Adding 'Active' Class On LI Navigation Works With preventDefault, But Link No Longer

jQuery删除了向li节点不起作用的添加活动类

Jquery removing an adding active class to li nodes not working

我知道删除活动类并添加到li的活动类以突出显示当前页面的导航项应该是非常基本的,但是我一直无法使其正常工作.

I know it should be really basic to remove and add the active class to li's in order to highlight the current page's nav item, but I've been unable to get it to work.

我发现必须使用e.preventDefault()使其起作用,但是当我这样做时,链接不起作用,但是突出显示的导航项起作用.如果我删除了preventDefault(),那么它将导航但不会突出显示.我应该说我的导航器位于header.php包含文件中.这就是我所拥有的:

I find that I must use e.preventDefault() to make it work, but when I do the link doesn't work but the highlighted nav item works. If I remove the preventDefault() then it navigates but doesn't highlight. I should say that my nav is sitting in a header.php include file. Here's what I have:

<ul class="myNav">
  <li><a href="index.php">Home</a></li>
  <li><a href="portfolio.php">Portfolio</a></li>
  <li><a href="about.php">About</a></li>
  <li><a href="contact.php">Contact</a></li>
</ul>

$('.myNav li a').click(function (e)
{
  e.preventDefault();
$('.myNav li').siblings().removeClass('active');
$(this).parent().addClass('active');
//var url = $(this).attr("href"); 
//window.location = url;
});

我试图将页面发送到单击的URL,这将加载正确的页面,但是会删除该类!我想解决此问题,但我也想了解为什么它无法正常工作.

I tried to send the page to the clicked url and this loads the correct page, but it removes the class! I'd like to solve this, but I'd also like to understand why it isn't working correctly.

推荐答案

我最终在PHP中这样做,如下:

I ended up doing it in PHP like this:

<?php
//grab the current page name to use in the
$path = $_SERVER['PHP_SELF'];
$page = basename($path);
$page = basename($path, '.php');
?>

        <li<?php if ($page == 'index') echo 'class="active"';?>><a href="index.php">Home</a></li>
    <li <?php if ($page == 'portfolio') echo "class='active'"; ?> ><a href="portfolio.php">Portfolio</a></li>
    <li <?php if ($page == 'about') echo 'class="active"'; ?> ><a href="about.php">About</a></li>
    <li <?php if ($page == 'contact') echo 'class="active"'; ?> ><a href="contact.php">Contact</a></li>

这篇关于jQuery删除活动类并将其添加到li节点&amp; preventDefault问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆