2015-05-16 38 views
-2

我无法用一个变量失去它的价值,我无法找到出现这种情况的原因,也许我错过的东西在这里..的js变量失去它的价值没有道理

function addToCart(item){ 

    if(cartItems === undefined){ 
     alert("nulling"); 
     var cartItems = 0; 
    } 

    var info = ["Nacho Sauchelli - Morgen 9", "Gaetano C - Airport", "Carmello Gargaglione Situation", "Irony (Paul DC Remix", "Proudly People - In the Factory", "Clap Contageon - Yellow Cup", "Fantini - Ricalibrae everything", "Dani rivas - Scroll", "Ben Grunnely - Bass Valve"]; 

    if(localStorage.getItem("username") == ""){ 
     alert("Cannot order, not logged in!"); 
    } 
    else{ 
     var items = 9; 
     var i = 0; 
     for(i=0;i<items;i++){ 
     if(i == item){ 
      var meme = document.getElementsByClassName("album"); 
      if(meme[i].style.opacity == '0.75'){ 
       meme[i].style.opacity = 1; 
       cartItems--; 
       }else{ 
       meme[i].style.opacity = .75; 
       meme[i].style.color = 'dodgerblue'; 
       cartItems++; 
       } 
     } 
    } 
    itemsInCart(cartItems); 
    } 
} 

function itemsInCart(cartItems){ 
    var cth = document.querySelector("#cartItemsHolder"); 
    cth.innerHTML = "Items In Cart:"+cartItems+""; 

} 

,每天进入未定义检查一次,我试着写了许多其他方面的发言,但我终于想通了,问题是其他地方

+0

真的吗?看看你的代码的前两行。你使用它的第一个地方是在if语句中,所以它当然是未定义的。 –

+0

@EdCottrell我怀疑OP的意图是变量是全局变量。 – Pointy

+0

@Pointy很可能,但这个问题显示没有真正努力去理解问题或提供一个MCVE。 –

回答

3

的问题就在这里:

function addToCart(item){ 

    if(cartItems === undefined){ 
    alert("nulling"); 
    var cartItems = 0; // problem here 
    } 

你已经有了cartItems声明那里通过那个var声明。这意味着cartItems是该函数中的局部变量,并且在每次新调用时都会新增undefined

如果cartItems旨在成为全局的,则不要在函数内声明它为var。你应该var功能被明确界定它,然而:

var cartItems = 0; 
function addToCart(item) { 
    // ... 
} 
+0

我也试过,它不会执行在这一切 –

+0

@ user3214998是的,它会。如果遇到问题,则需要将问题的详细信息作为问题的一部分发布。 – Pointy

+0

我在铬控制台没有得到任何错误,我认为它没有执行,因为我甚至没有得到警报。如果我把var返回,它就起作用了 –