【问题标题】:remove # inside a href attribute of an anchor tag how在锚标记的 href 属性中删除 # 如何
【发布时间】:2015-05-09 15:35:58
【问题描述】:

我正在制作一个选项卡,其概念是当一个人单击选项卡菜单时,jquery 将检查该锚标记(选项卡菜单)的 href 属性并删除其中的 # 并保留该属性的其余 attr 内容(参考)。例如

<a href="#home" class="tabmenu">Tab 1</a><a href="#inventory" class="tabmenu>Tab 2</a>
<div id="home" class="tab">content of tab 1 here</div>
<div id="inventory" class="tab">content of tab 2 here</div>

所以当单击选项卡菜单之一时。 jquery 将删除该锚标记 href 属性的 #,因此 href 属性将是 this href="home" (如果单击选项卡 1),然后 jquery 将首先隐藏所有选项卡内容 div (.tab),然后显示内容具有 #home 的选项卡(如果单击选项卡 1)。

所以脚本概念看起来像这样:

$(document).ready(function(){
    $('.tabmenu').click(function(){
        //get the anchor tag attr
        //remove # inside this anchor tag href attribute and the remaining content will be put in a variable
        //hide all tab content first
        //get the stored variable and then show the tab content that match of that stored variable e.g. (home or inventory).
    });
});

任何帮助将不胜感激。谢谢!

【问题讨论】:

标签: javascript jquery


【解决方案1】:

如果您希望在用户单击选项卡时仅显示匹配的内容,您可以使用以下代码:

$(document).ready(function(){    
    $('.tabmenu').click(function(){
        //hide all:
        $(".tab").hide();
        //show clicked tab:
        $("#" + $(this).attr('href').substring(1)).show();
    });
});

工作小提琴:http://jsfiddle.net/x29gn8yo/

【讨论】:

    【解决方案2】:

    不知道为什么要更改 href 属性,甚至对你正在做的事情都没有必要,但也许你需要这个来做其他事情,所以你去吧:

    $(document).ready(function(){
        $('.tabmenu').click(function(){
    
            //get the anchor tag attr
            var href = $(this).attr('href');
    
            //remove # inside this anchor tag href attribute and the remaining content will be put in a variable
            if (href[0] == '#') {
                this.attr('href') = href.substring(1);
            }
    
            //hide all tab content first
            $('.tab').hide();
    
            //get the stored variable and then show the tab content that match of that stored variable e.g. (home or inventory).
            $(href).show();
        });
    });
    

    请注意,由于我们更改了 href 属性,因此此代码仅对每个链接有效一次。如果你愿意,我可以修改它以使用更改后的属性。

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2020-09-08
      • 1970-01-01
      • 2022-08-08
      • 2012-06-08
      • 2021-09-23
      相关资源
      最近更新 更多