简体   繁体   English

如何使用 JavaScript 将变量作为元素 ID 应用?

[英]How can I apply a variable as an element ID with JavaScript?

I saw in the firebug the ID is like this whereas I want the value of existingProductArray[i] to be the ID.我在萤火虫中看到 ID 是这样的,而我希望existingProductArray[i]的值是 ID。 What am I doing wrong?我究竟做错了什么?

var html ='<li id="existingProductArray[i]">'
       + '<input type="image" id="existingProductArray[i]" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
       + existingProductArray[i]
       + '</li>';
     

Try this尝试这个

 var id = existingProductArray[i];

 var html ='<li id="' + id + '">'
           + '<input type="image" id="' + id + '" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
           + id
           + '</li>';

But

ID hence the name should be unique you are giving 2 elements the same ID ( that's a bad idea ) ID 因此名称应该是唯一的,您为 2 个元素提供相同的 ID(这是一个坏主意)

Try changing:尝试改变:

+ '<input type="image" id="existingProductArray[i]" src="...>'

to

+ '<input type="image" id="'+existingProductArray[i]+'" src="...>'

So in your line of code it was just using it as text string.因此,在您的代码行中,它只是将其用作文本字符串。 You need to break out of the string and do it.您需要跳出字符串并执行此操作。

I stumbled upon the same problem, I know my problem is not 100% the same as yours but I bet I can help other people out who search for this kind of problem.我偶然发现了同样的问题,我知道我的问题与您的问题不是 100% 相同,但我敢打赌,我可以帮助其他寻找此类问题的人。

I was trying to add a variable as a ID name for a div.我试图添加一个变量作为 div 的 ID 名称。 I tried several methods mentioned above but none of those seemed to work.我尝试了上面提到的几种方法,但这些方法似乎都不起作用。

I did the following:我做了以下事情:

div.id = array[i];

which in your case would have simply been:在你的情况下,这只是:

id=existingProductArray[i];

No " " or + needed, don't forget to declare the i variable.不需要 " " 或 +,不要忘记声明i变量。 This might be very obvious for some people with more experience.对于一些有更多经验的人来说,这可能非常明显。

You just need to close the quotes and concatenate it in with + :您只需要关闭引号并将其与+连接起来:

var html ='<li id="existingProductArray[i]">'
               + '<input type="image" id="' + existingProductArray[i] + '" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
               + existingProductArray[i]
               + '</li>';

your reference is inside the quotations您的参考在引号内

       var html ='<li id="'+existingProductArray[i]+'">'
               + '<input type="image" id="'+existingProductArray[i]+'" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
               + existingProductArray[i]
               + '</li>';

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

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