【问题标题】:Get the href value and then find it as an id获取href值,然后作为id查找
【发布时间】:2017-01-23 14:18:34
【问题描述】:

我正在尝试基于锚导航构建此部分。当我单击一个链接时,我会到达所需的锚点,并且单击的链接会获得一个具有特定样式的类,到目前为止它运行良好:

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 中的值,但这不起作用,它返回 undefined:

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

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

这行得通吗?我必须如何填写查找查询?

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

【问题讨论】:

  • 为了正确获取 href:请改用:var href = $("a", this).attr('href');

标签: jquery anchor


【解决方案1】:

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

还有 jquery sn-p:

$(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 + " !");
   });
});

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

通过这样做:$("a", this).attr('href') 你告诉获取我刚刚单击的 div 中 &lt;a&gt; 元素的 href 属性的值

之后你可以用$(href)选择对应的div

【讨论】:

    【解决方案2】:

    您正在尝试获取&lt;div&gt;href,但它没有该属性

    将选择器更改为 &lt;a&gt; 或使用 find() 查看 div 内部

    $(".anchor-link").on("click", function(){
       var href = $(this).find('a').attr('href');
      ....
    
    })
    

    【讨论】:

      【解决方案3】:

      尝试以下点击处理程序

      $(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);
         });
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-20
        • 2014-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-14
        • 1970-01-01
        相关资源
        最近更新 更多