获取 href 值,然后将其作为 id 查找

Get the href value and then find it as an id

我正在尝试基于锚导航构建此部分。当我单击 link 时,我到达了所需的锚点,单击的 link 获得了具有特定样式的 class,到目前为止效果很好:

HTML

<body>

  <nav>
    <div class="anchor-link" > <a href="#anchor1" > Anchor 1 </a> </div>
    <div class="anchor-link"> <a href="#anchor2"> Anchor 2 </a> </div>
    <div class="anchor-link"> <a href="#anchor3"> Anchor 3 </a> </div>
    <div class="anchor-link"> <a href="#anchor4"> Anchor 4 </a> </div>
    <div class="anchor-link"> <a href="#anchor5"> Anchor 5 </a> </div>
  </nav>

  <div class="main-wrap">
    <div id="anchor1"></div>
    <div id="anchor2"></div>
    <div id="anchor3"></div>
    <div id="anchor4"></div>
    <div id="anchor5"></div>
   </div>

</body>

JS

$(document).ready(function(){
  $(".anchor-link").on("click", function(){
    $(this).addClass("active");
    $(this).siblings().removeClass("active");

现在我想获取 href 中的值,但这不起作用,而且它 returns 未定义:

      var href = $(this).attr('href');
      console.log(href);
   })

假设它有效,并且 var href 保存了点击的 link 的值,例如“#anchor1”,我将如何继续在 "main-wrap" 中找到, div ID 为“#anchor1”?

这行得通吗,我将如何填写该查找查询?

$(".main-wrap").find(...);

您正在尝试获取 <div>href,但它没有该属性

将选择器更改为 <a> 或使用 find()

查看 div 内部
$(".anchor-link").on("click", function(){
   var href = $(this).find('a').attr('href');
  ....

})

这是一个 jsFiddle 做你想做的事:jsFiddle

还有 jquery 片段:

$(document).ready(function(){
  $(".anchor-link").on("click", function(){
    $(this).addClass("active");
    $(this).siblings().removeClass("active");
      var href = $("a", this).attr('href');
      $(href).html("You clicked " + href + " !");
   });
});

您试图获取引用 <div class="anchor-link" >$(this) 元素的 href,但它没有任何 href 属性。

这样做:$("a", this).attr('href')你告诉取div中<a>元素的href属性的值我刚刚点击

之后你可以select对应的div和$(href)

尝试以下点击处理程序

$(document).ready(function(){
  $(".anchor-link a").on("click", function(){
    $(this).parents('.anchor-link').addClass("active");
    $(this).parents('.anchor-link').siblings().removeClass("active");
      var href = $(this).attr('href');
      console.log(href);
   });
})