Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 变量不';行不通_Javascript - Fatal编程技术网

Javascript 变量不';行不通

Javascript 变量不';行不通,javascript,Javascript,出于某种奇怪的原因,下面的代码不起作用 var xxx = localStorage.getItem('position'); var foo = document.querySelectorAll("div[current_position=' + xxx + ']"); for (var i = 0; i < foo.length; i++) { // ... } 然后代码就可以正常工作了。但是如果我将'2'更改为'+xxx+',它就不起作用了 对原始问题进行了编辑。多亏了B

出于某种奇怪的原因,下面的代码不起作用

var xxx = localStorage.getItem('position');
var foo = document.querySelectorAll("div[current_position=' + xxx + ']");
for (var i = 0; i < foo.length; i++)
{
    // ...
}
然后代码就可以正常工作了。但是如果我将
'2'
更改为
'+xxx+'
,它就不起作用了


对原始问题进行了编辑。多亏了Bhojendra Nepal和Jonah Williams。

问题在于
xxx
是一个指向本地存储的变量,而
“xxx”
只是一个字符串。您需要在字符串中插入值

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

您需要将变量与字符串连接起来:

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

此外,我建议您对有效的html5元素使用
data-*
属性,因此使用
data current position
而不是
current\u position
好的,我自己找到了解决方案。代码的第二行应该是:

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

还有所有的工作。

对不起,那是我的错失,我忘了
'
+
。出于某种奇怪的原因,它不起作用。此外,根据此更正,原始问题已被编辑。您仍然存在连接问题。
var foo = document.querySelectorAll("div[current_position='" +xxx+ "']");