单击链接打开页面后,在页面中显示隐藏的div

时间:2015-09-21 11:38:18

标签: javascript jquery html css

我有一个HTML页面,当单击按钮时,隐藏的div变为可见。像这样:

$('#display').click(function(){
    $('#itemList').removeClass('hide');
    ...
})

在另一个页面上,有一个链接,点击后会将用户带回到前一页,并且该页面上id = 'itemList'的元素必须可见。代码是这样的:

<a href='firstHTML.php'> View items</a>

我不知道还有什么可以添加到代码中以使其他页面显示以前隐藏的元素可见。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

最可能的解决方案之一是localStorage。您也可以实现Cookie或字符串查询以将值传递给其他页面。

我正在展示localstorage的使用,你可以在点击锚点时将id存储在localStorage中,如下所示

<a href='firstHTML.php' data-showId='itemList'> View items</a>

现在在锚点上绑定事件

$("[data-showId]").bind('click',function(){
    var idToShow=$(this).attr('data-showId');
    if(idToShow)
      store('visibleId', idToShow);
});

现在您需要定义这些功能。

   function setup() {
        var tmp = get('visibleId');
        if (tmp)
          showDiv(tmp);
    } 
    function showDiv(cls) {
        $("#"+cls).removeClass('hide');
    }
    function get(name) {
        if (typeof (Storage) !== "undefined") {
          return localStorage.getItem(name);
        } else {
          window.alert('Please use a modern browser to properly view this template!');
        }
    }
    function store(name, val) {
        if (typeof (Storage) !== "undefined") {
          localStorage.setItem(name, val);
        } else {
          window.alert('Please use a modern browser to properly view this template!');
        }
    }

现在在dom上调用setup()..

答案 1 :(得分:0)

首先,我会使用jQuery函数隐藏/显示List而不是使用自己的CSS类:

$('#display').click(function(){
    $('#itemList').show();
    ...
})

然后,您的问题的可能方法可能是使用get参数,例如:

<a href='firstHTML.php?list=show'> View items</a>

使用jQuery

  1. 创建一个辅助函数(取自Get url parameter jquery Or How to Get Query String Values In js):

    $.urlParam = function(name) {
    
      var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    
      if (results==null){
        return null;
      }else{
       return results[1] || 0;
      } 
    }
    
  2. 宣读财产:

    var listStatus = $.urlParam('list');
    
  3. 取消隐藏列表,以防它显示:

    $( document ).ready(function() { 
      if(listStatus == 'show') {
        $('#itemList').show();
      }
    });
    
相关问题