单击Jquery addClass()不起作用,什么都不做

时间:2017-02-23 03:02:22

标签: javascript jquery html css

嗯,它基本上都在标题中。我无法获取我的Jquery脚本来向div添加一个类。

HTML

<div class="nav">
<div id="link">Home</div>
<div id="link">Roms</div>
<div id="link">FAQ</div>
<div id="link">About</div>
</div>

CSS

  .nav {
    width: 100%;
    height: 44px;
    box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
    margin-bottom: 2px;
    border-top: 1px solid black;
    background-image: url(../img/header.jpg);
    background-size: contain;
    display: inline-block;
    opacity: 0.9;
}
#link {
    float: left;
    color: #f9fcfd;
    width: 20%;
    margin-left: 2.5%;
    margin-right: 2.5%;
    text-align: center;
    line-height: 50px;
    font-family: 'Overpass';
    font-size: 100%;
    font-weight: bolder;
    transition: 0.3s ease-in-out;
}
#link:hover {
    opacity: 0.7;
}
.active {
    border-bottom: 2px solid #28d7d7;
    transition: ease-in-out 0.3s;
    border-radius: 5px;
}

JQuery

$(function() {
  $("#link").click(function() {
    $(this).addClass("active");
  }); 
});

2 个答案:

答案 0 :(得分:0)

您无法复制身份link。将id="link"更改为class="link"

HTML:

<div class="nav">
  <div class="link">Home</div>
  <div class="link">Roms</div>
  <div class="link">FAQ</div>
  <div class="link">About</div>
</div>

CSS:

.nav {
  width: 100%;
  height: 44px;
  box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
  margin-bottom: 2px;
  border-top: 1px solid black;
  background-image: url(../img/header.jpg);
  background-size: contain;
  display: inline-block;
  opacity: 0.9;
}
.link {
  float: left;
  color: #f9fcfd;
  width: 20%;
  margin-left: 2.5%;
  margin-right: 2.5%;
  text-align: center;
  line-height: 50px;
  font-family: 'Overpass';
  font-size: 100%;
  font-weight: bolder;
  transition: 0.3s ease-in-out;
}
.link:hover {
  opacity: 0.7;
}
.active {
  border-bottom: 2px solid #28d7d7;
  transition: ease-in-out 0.3s;
  border-radius: 5px;
}

JQUERY:

$(document).ready(function(){
   $(function() {
     $(".link").click(function() {
     $(this).addClass("active");
     }); 
   });
});

答案 1 :(得分:0)

我认为你应该将id改为class和

    $(".link").click(function() {
        $(this).addClass("active").siblings("div").removeClass("active");
    });