使用 jquery 切换引导程序活动导航链接



我正在尝试合并一个jquery函数,以自动更改我的Bootsrap导航栏中nav链接的活动状态。 我有一个基本 HTML 文件,该文件可扩展到特定于应用程序的基本文件中。 然后将该文件扩展到navbar导航的各个页面。

以下是特定于应用程序的 HTML:

{% extends "base.html" %}
{% load static %}
{% block css %}
<link rel="stylesheet" href="{% static 'home/main.css' %}">
{% endblock css %}
{% block js %}
<script>
$(function() {
$("#home-navs").click(function() {
// remove classes from all
$("#home-navs").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
});
});
</script>
{% endblock js %}
{% block content %}
<br>
<div class="container status-update">
<div class="container">
<form>
<div class="input-group-lg">
<input type="text" class="form-control" value="What's new?">
</div>
<br style="height:20px">
<button type="submit" class="btn btn-primary btn-lg" name="button">Post</button>
</form>
</div>
</div>
<br>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #6298bf">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<div class="navbar-nav">
<a class="nav-link active" id="home-navs" href="{% url 'home' %}">Activity Feed</a>
<a class="nav-link" id="home-navs" href="{% url 'vehicle-updates' %}">Vehicle Updates</a>
<a class="nav-link" id="home-navs" href="/space.html">Garage Updates</a>
</div>
</div>
</nav>
</div>

然后我在我的主base.html文件的头部有这个:

{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
{% block css %}{% endblock css %}

<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
{% block js %}{% endblock js %}

<title>Test</title>
</head>

页面和链接工作正常,当我单击不同的链接时,我只是无法更改navbar上的active状态。 我不知道我是否错误地引用了函数中的项目,还是什么。 任何指导将不胜感激。谢谢!

不能将 id 用于多个 dom 元素。请改用类。

尝试将其更改为:

$(".nav-link").click(function() {
// remove classes from all
$(".nav-link").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
});

如果你想把它的范围限定为只有特定导航的元素,把id放在导航本身,然后使用选择器:$("#main-nav .nav-link")

最新更新