简体   繁体   中英

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. No error here.

  2. current_position is a number (1, 2, 3, ... etc). If I manually set, for example, '2' , like below:

     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.

Original question was edited. Thanks to Bhojendra Nepal and 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

the problem is that xxx is a variable pointing to localstorage, and "xxx" is just a string. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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