简体   繁体   English

变量和字符串的串联错误

[英]Concatenation of variable and String wrong

I would like to pass an argument to another page but it turns out that it's undefined. 我想将一个参数传递给另一个页面,但事实证明它是未定义的。

getAccount() returns a list of json. getAccount()返回json列表。 Firstly, I display those json objects one by one on HTML and when the user clicks each, the accDetail[i].accNo is set as local storage and will be passed to next page. 首先,我在HTML上逐一显示这些json对象,当用户单击每个json对象时,accDetail [i] .accNo设置为本地存储,并将传递到下一页。

var accDetail=getAccounts();


for(var i =0;i<accDetail.length;i++) {
  document.getElementById("demo").innerHTML+='<a href="accountdetails.html" onclick="getAcc('+accDetail[i].accNo+')">'+accDetail[i].accNo +'</a>'+' '+ accDetail[i].accType+' '+ accDetail[i].balance+'<br>';

} }

This is the function to set the item as local storage. 这是将项目设置为本地存储的功能。

function getAcc(item)
{
    localStorage.setItem("accNo",item); }

It does not display the value I want, is the way I concatenate it wrong? 它不显示我想要的值,我将其连接的方式错误吗?

Your onclick handler is going to be literally getAcc(accDetail[i].accNo) (try viewing in Inspect Element), which won't work because accDetail is not defined in the event handler. 您的onclick处理程序实际上将 getAcc(accDetail[i].accNo) (尝试在Inspect元素中查看),该方法将不起作用,因为事件处理程序中未定义accDetail You need to change your Javascript so that it writes getAcc(0) , getAcc(1) , etc where 0, 1 are the different accNo . 您需要更改Javascript,以使其写入getAcc(0)getAcc(1)等,其中0、1是不同的accNo

Here is a small example I wrote, hopefully you can extend it to solve your problem: 这是我写的一个小例子,希望您可以扩展它来解决您的问题:

var accNo = [1, 2, 3, 4];
  for(var i = 0;i < accNo.length; i++) {
    var line = '<a href="accountdetails.html" onclick="getAcc(' + accNo[i] + ')">' + accNo[i] + '</a> <br>';
    console.log(line);
    document.getElementById("demo").innerHTML += line;
  }

First Make sure your function getting correct value 首先确保您的函数获得正确的值

Try Using window object instead 尝试改为使用窗口对象

function getAcc(item)
{
    localStorage.setItem("accNo",item); 
}

Replace with 

function getAcc(item) 函数getAcc(item)
{ {
console.log(item); console.log(item); // Please check you get item correct not undefined // 请检查您是否获得了正确且未定义的项目
window.accNo = item; window.accNo =项目;
} }

And whereever you want just use window.accNo 而只要您想使用window.accNo

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

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