【问题标题】:How to set id of next element into href attribute of link using jquery?如何使用 jquery 将下一个元素的 id 设置为链接的 href 属性?
【发布时间】:2016-09-26 20:02:30
【问题描述】:

我必须为许多 html href 属性(一个标签)分配紧随其后的各自 id 的值。 使用我的代码,我只得到一个值(第一个)。 非常感谢。 朱里

$(".anchor").attr("href","#"+($(".anchor").closest("div").next("div").attr("id")));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
    <a class="anchor">Get anchor 1</a>
</div>
<div id="link1">
    <p>A paragraph</p>
</div>
<div>
    <a class="anchor">Get anchor 2</a>
</div>
<div id="link2">
    <p>Another paragraph</p>
</div>

【问题讨论】:

  • 您的问题解决了吗?
  • @Mohammad 是的,非常感谢,你们都是最棒的

标签: javascript jquery html attributes href


【解决方案1】:

您需要所选元素的实例。可以使用attr(attrName, function)来实现

$(".anchor").attr("href",function(){
    return '#' + $(this).closest("div").next("div").attr("id");
});

【讨论】:

    【解决方案2】:

    Jquery .attr() 在第二个参数中带有函数,迭代选定的元素并更改其属性。也使用.parent() 而不是.closest("div")

    $(".anchor").attr("href", function(){
        return "#"+$(this).parent().next("div").attr("id");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
        <a class="anchor">Get anchor 1</a>
    </div>
    <div id="link1">
        <p>A paragraph</p>
    </div>
    <div>
        <a class="anchor">Get anchor 2</a>
    </div>
    <div id="link2">
        <p>Another paragraph</p>
    </div>

    【讨论】:

      【解决方案3】:

      循环遍历所有具有类锚的 a 标签并使用 $(this).parent("div").next("div").attr("id")) 选择器获取 a 标签的链接。

      请检查下面的sn-p。

      $(".anchor").each(function(){
        $(this).attr("href","#"+($(this).parent("div").next("div").attr("id")));
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      
      <div><a class="anchor">Get anchor 1</a>
      </div>
      <div id="link1">
      <p>A paragraph</p>
      </div>
      
      <div><a class="anchor">Get anchor 2</a>
      </div>
      <div id="link2">
      <p>Another paragraph</p>
      </div>

      【讨论】:

        【解决方案4】:

        使用 jQuery eachforwhile 等任何循环来迭代所有 .anchor 元素。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-15
          • 1970-01-01
          • 2016-07-09
          • 1970-01-01
          • 1970-01-01
          • 2021-04-12
          • 2010-09-15
          相关资源
          最近更新 更多