试图比较本地存储字符串与url字符串不工作

trying to compare local storage string to url string not working

本文关键字:字符串 url 工作 存储 比较      更新时间:2023-09-26

这是我尝试做的基本前提:

假设你有一个简单的嵌套列表:

<ul>
   <li>chevy</li>
   <li>dodge</li>
   <li id="trucks">ford
      <ul>
        <li>ranger</li>
        <li>f150</li>
        <li>f250</li>
      </ul>
   </li>
   <li>kia</li>
</ul>

默认情况下,隐藏嵌套的ford菜单选项。一旦点击"ford"链接,当新页面打开时,嵌套的"ranger","f150"answers"f250"div将打开并显示嵌套的菜单。

我的想法是在点击事件上抓取<li>的id,将其作为字符串放在localStorage中,然后在新页面加载,将url子字符串与本地存储字符串进行比较,如果它们匹配,则放置一类display: block,然后使菜单可见。

这是我迄今为止拥有的jQuery,但是当我试图比较两者时,我一直得到"不",说它们不一样。这是我现在想不通的一件事。

//get the id on the div and then store as a string
function storeId() {
    $mtv('.features > ul > li > a').click(function() {
        var name = $mtv (this).attr('id');
        localStorage.setItem( 'name', JSON.stringify(name) );
    });
};
//retrieve the storage item and compare to id clicked
function retrieveId() {
    localStorage.getItem( 'name' );
    var retrieve = localStorage.getItem('name');
    var url = window.location.pathname;
    var currentUrl = url.substring(url.lastIndexOf('/')+1).replace('.html', '');
    if (currentUrl === retrieve ){
        alert("yes");
    }
    else {
        alert("no")
    }
};

任何帮助都非常感谢,

D

使用var name = $mtv(this).attr('id');,您正在尝试获取链接的id

当你想要获取li的id时试试这个-

var name = $mtv(this).closest('li').attr('id');