【问题标题】:Adding an anchor to generated URLs向生成的 URL 添加锚点
【发布时间】:2010-10-22 06:19:03
【问题描述】:

我已经尝试找到一个类似的示例并用它来回答我的问题,但我似乎无法让它工作,所以如果这听起来与其他问题相似,请道歉。

基本上,我使用 Terminal Four 的 Site Manager CMS 系统来构建我的网站。此工具允许您生成导航元素以在整个网站中使用。

我需要添加一些自定义的 JS 来为这些链接附加一个锚点。

生成的链接是这样的:

<ul id="tab-menu">
<li><a href="/section/page">test link, can i rewrite and add an anchor!!!</a></li>
</ul>

我可以编辑链接的 css 属性,但不知道如何添加锚点。

我使用的JQuery如下:

<script type="text/javascript" src="http://jquery.com/src/jquery-latest.pack.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    // everything goes here

    $("#tab-menu").children("li").each(function() { 
        $(this).children("a").css({color:"red"});

        });

    });
</script>

提前感谢您的帮助。

稻田

【问题讨论】:

  • 好问题,但是没有 jQuery 怎么办?

标签: javascript jquery append anchor


【解决方案1】:

我不确定答案,我尝试一下

$("#tab-menu").children("li").children("a").each(function() {   
              //  $(this).css({color:"red"}).get(0).hash = "boom";
            var temp_url = $(this).href +'#an_anchor';//or var temp_url = $(this).attr('href');
          $(this).attr('href', temp_url);
    });

【讨论】:

    【解决方案2】:

    一个不错的基于 jQuery 的方法是使用 .get(index) 方法访问 each() 函数中的原始 DOM 元素。然后,您可以访问 JavaScript 链接对象,该对象有一个名为“hash”的属性,表示 url 的锚部分。所以稍微修改你的代码:

    <script type="text/javascript">
        $(document).ready(function(){
        // everything goes here
    
            $("#tab-menu").children("li").children("a").each(function() {   
                $(this).css({color:"red"}).get(0).hash = "boom";
            });
    
        });
    

    将“#tab_menu li”中的所有链接更改为红色,并在末尾附加“#boom”。

    希望这会有所帮助!

    【讨论】:

    • 酷。没有 jQuery 怎么办?
    【解决方案3】:

    我现在可以使用以下内容来定位 html:

    $(this).children("a").html("it works");
    

    我假设:

    $(this).children("a").href("something");
    

    会编辑 href 但我错了。

    稻田

    【讨论】:

    • 使用类似 $(this).children("a").attr("href","something") 就可以了。
    【解决方案4】:

    有点重复: How to change the href for a hyperlink using jQuery

    只需复制旧的 href 并将锚点添加到它并粘贴回来

    var link = $(this).children("a").attr("href");
    $(this).children("a").attr("href", link+ "your own stuff");
    

    【讨论】:

      猜你喜欢
      • 2014-10-20
      • 2017-08-17
      • 2023-03-17
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 2013-08-06
      相关资源
      最近更新 更多