刷新页面后保持相同的选项卡

时间:2017-01-14 21:51:13

标签: jquery

$(function () {
    // constants
    var SHOW_CLASS = 'show',
        HIDE_CLASS = 'hide',
        ACTIVE_CLASS = 'active';

    $('.tabs').on('click', 'li a', function (e) {
        e.preventDefault();
        var $tab = $(this),
             href = $tab.attr('href');


        $('.active').removeClass(ACTIVE_CLASS);
        $tab.addClass(ACTIVE_CLASS);

        $('.show')
           .removeClass(SHOW_CLASS)
           .addClass(HIDE_CLASS)
           .hide();

        $(href)
          .removeClass(HIDE_CLASS)
          .addClass(SHOW_CLASS)
          .hide()
          .fadeIn(550);
    });
});

我已尝试过隐藏字段方法,但不知何故,我仍然无法在刷新后停留在同一个标​​签页上。以上是我在JS文件中的代码。

2 个答案:

答案 0 :(得分:0)

您可以将锚点添加到链接中,并使用location.hash从网址中获取哈希值。

如果没有e.preventDefault();标记,则不需要href,您可以使用data属性。

答案 1 :(得分:0)

            In React JS,

            I am using localstorage here to save the data.

            Add onClick function on each <li> 
            eg: onClick={()=>this.handleClick("your arg")}

            call this function: 
                handleClick=(arg)=>{
               localStorage.setItem("name",arg);
                }

        define state, this.state = {
                    history:true,
                    outgoing:false,
                    incoming:false,
                };

    in componentDidMount get the data from localstorage,

    eg:
      componentDidMount=()=>{
        let activeTab = localStorage.getItem("name");
      switch(activeTab){
            case 'History':
                this.setState({
                    history:true,
                    outgoing:false,
                    incoming:false,
                    confirmed:false
                })
                break;
                case 'Outgoing':
                        this.setState({
                            history:false,
                            outgoing:true,
                            incoming:false,
                            confirmed:false
                        })
                        break;
                        case 'Incoming':
                                this.setState({
                                    history:false,
                                    outgoing:false,
                                    incoming:true,
                                    confirmed:false
                                })
    }

than, use the ternary operator in two place

1> className={`nav-link js-animation-link btn btn-outline-light btn-wide 
    ${this.state.history ? "active":""}`}
2>  aria-selected={this.state.history ?"true" :"false"}

use the same ternary operator in "tab-content" as well.