简体   繁体   English

变量不起作用

[英]Variable doesn't work

For some strange reason the code below doesn't work. 由于某些奇怪的原因,下面的代码无法正常工作。

var xxx = localStorage.getItem('position');
var foo = document.querySelectorAll("div[current_position=' + xxx + ']");
for (var i = 0; i < foo.length; i++)
{
    // ...
}

Some facts: 一些事实:

  1. The localStrorage work correct - localStorage.getItem('position') outputs the correct value. localStrorage工作正常localStrorage localStorage.getItem('position')输出正确的值。 No error here. 这里没有错误。

  2. current_position is a number (1, 2, 3, ... etc). current_position是一个数字(1、2、3等)。 If I manually set, for example, '2' , like below: 如果我手动设置,例如'2' ,如下所示:

     var foo = document.querySelectorAll("div[current_position='2']"); 

    then the code work as it should. 然后代码按预期工作。 But if I change '2' to a ' + xxx + ' , it doesn't work. 但是,如果我将'2'更改为' + xxx + ' ,则无法使用。

Original question was edited. 原始问题已编辑。 Thanks to Bhojendra Nepal and Jonah Williams. 感谢尼泊尔Bhojendra和Jonah Williams。

You need to concatenate your variable with strings: 您需要将变量与字符串连接起来:

var xxx = localStorage.getItem('position');
var foo = document.querySelectorAll("div[current_position=" + xxx + "]");
for (var i = 0; i < foo.length; i++)
{
    // ...
}

Moreover, I would suggest you to use data-* attribute for valid html5 elements, so use data-current-position instead of current_position 此外,我建议您将data-*属性用于有效的html5元素,因此请使用data-current-position而不是current_position

the problem is that xxx is a variable pointing to localstorage, and "xxx" is just a string. 问题是xxx是一个指向localstorage的变量,而"xxx"只是一个字符串。 You need to insert the value into your string, 您需要将值插入字符串,

document.querySelectorAll("div[current_position=" + xxx + "]");

Ok, I found the solution myself. 好的,我自己找到了解决方案。 The second line of the code should be: 代码的第二行应为:

var foo = document.querySelectorAll("div[current_position='" +xxx+ "']");

And all works. 和所有的作品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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