如何更新span标签的内容?

如何更新span标签的内容?

问题描述:

我正在创建一个网页,用户通过点击按钮选择一个项目。所选项目的详细信息将显示在保管箱中。目前,如果用户再次选择数量,我可以更新数量。我遇到的问题是,如果用户首先点击btnBuy1(细节显示在保存箱中),然后点击btnBuy2(同样会显示细节),但是当他们再次点击btnBuy2时,会更新btnBuy2的详细信息,但是来自btnBuy1的详细信息消失。如何更新span标签的内容?

 $("#btnBuy0").click(function() 
     { 
      if (!sessionStorage['quantity0']) 
      { 
       sessionStorage['quantity0'] = 1; 
       $("#dropbox").append('<span id = "0"><img class = "thumb" src="../images/21_metoyou.jpg" />' + teddy[0].desc + ", Price £" 
      + teddy[0].price + ", Quantity: " + sessionStorage.getItem('quantity0') + "</span><br/>"); 

      }   
      else 
      { 
       sessionStorage['quantity0']++; 
       $("#dropbox").html('<span id = "0"><img class = "thumb" src="../images/21_metoyou.jpg" />' + teddy[0].desc + ", Price £" 
      + teddy[0].price + ", Quantity: " + sessionStorage.getItem('quantity0') + "</span><br/>"); 

      } 
      if (Modernizr.sessionstorage) 
      { // check if the browser supports sessionStorage 
       myids.push(teddy[0].partnum); // add the current username to the myids array 
       sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage 
      } 
      else 
      { 
      // use cookies instead of sessionStorage 
      } 
     }); 
     $("#btnBuy1").click(function() 
     { 
      if (!sessionStorage['quantity1']) 
      { 
       sessionStorage['quantity1']=1; 
       $("#dropbox").append('<span id = "1"><img class = "thumb" src="../images/birthday_metoyou.jpg" />' + teddy[1].desc + ", Price £" 
      + teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "</span><br/>"); 

      } 
      else 
      { 
       sessionStorage['quantity1']++; 
       $("#dropbox").html('<span id = "1"><img class = "thumb" src="../images/birthday_metoyou.jpg" />' + teddy[1].desc + ", Price £" 
      + teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "</span><br/>"); 

      } 
      if (Modernizr.sessionstorage) 
      { // check if the browser supports sessionStorage 
       myids.push(teddy[1].partnum); // add the current username to the myids array 
       sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage 
      } 
      else 
      { 
      // use cookies instead of sessionStorage 
      } 
     }); 

我不是一个jQuery的人,但我觉得你的问题是,你递增计数,然后替换保管箱所有HTML造成的事实 - 可见

sessionStorage['quantity0']++; 
    $("#dropbox").html('<span id = "0"><img class = "thumb" src="..jpg" />' + 
// there -------^^^^----- 
         teddy[0].desc + ", Price £" 
        + teddy[0].price + ", Quantity: " + 
         sessionStorage.getItem('quantity0') + "</span><br/>"); 

不该你是不是替换$(“#0”)而不是$(“#dropbox”)的内容? ...即

sessionStorage['quantity0']++; 
    $("#0").html('<img class = "thumb" src="..jpg" />' + teddy[0].desc + 
        ", Price £" + teddy[0].price + ", Quantity: " + 
        sessionStorage.getItem('quantity0'));