简体   繁体   中英

remove # inside a href attribute of an anchor tag how

im making a tab and the concept is when a person click on the tab menu, jquery will then check on the href attribute of that anchor tag (tab menu) and remove # inside it and leaves the rest attr content of that attribute (href). for example

<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>

so when one of the tab menu is clicked. jquery will remove the # of that anchor tag href attribute, therefore the href attribute will be this href="home" (if tab 1 is click) and then jquery will hide all tab content div first (.tab) and then show the content tab that has #home (if tab 1 is click).

so the script concept will somehow look like this:

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

any help would be greatly appreciated. thank you!

Not sure why you want to change the href attribute, it's not even necessary for what you're doing, but maybe you need this for something else, so here you go:

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

Please be aware that this code only works once for every link since we change the href attribute. I can modify it to work with the changed attribute if you want to.

If you want the show only the matching content when the user click the tabs, you can use this code:

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

working fiddle: http://jsfiddle.net/x29gn8yo/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM