在localStorage中存储标题不起作用

时间:2017-02-03 15:48:51

标签: javascript jquery local-storage

如何在localStorage中存储标题?

例如:

if (document.querySelector('li.selection').title != " ") {
      localStorage.setItem('test', document.querySelector('li.selection').title);
}

我已收到"undefined"部分value部分。

2 个答案:

答案 0 :(得分:1)

您可以尝试如下

<p><abbr id="myAbbr" title="World Health Organization">WHO</abbr> was founded in 1948.</p>

<button onclick="myFunction()">Try it</button>
<button onclick="myFunction1()">receive</button>
<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myAbbr").title;
    window.localStorage.setItem('test', x);
}
function myFunction1() {
    var x = window.localStorage.getItem('test');
    document.getElementById("demo").innerHTML = x;

}
</script>

W3schools snippet

同时检查如果要比较空字符串,则不需要在引号之间指定space。这也可能是您未定义的原因,因为该值可能未定义且不是space且条件已经过去。

if (document.querySelector('li.selection').title != "") {
      localStorage.setItem('test', document.querySelector('li.selection').title);
}

答案 1 :(得分:0)

首先,你在条件title != " "中有if title does not equal **one space** ...这意味着如果标题不是一个空白字符,那么条件总是正确的而且可能是例如undefined。

您是否尝试使用空字符串"")或undefined替换空格?

我建议您使用element.getAttribute("title")函数,这比直接访问title属性更好。