开发者

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

开发者 https://www.devze.com 2023-03-25 16:19 出处:网络
I saw in the firebug the ID is like this whereas I want the value of existingProductArray[i] to be the ID. What am I doing 开发者_如何学编程wrong?

I saw in the firebug the ID is like this whereas I want the value of existingProductArray[i] to be the 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 )


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.


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>';


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.

I was trying to add a variable as a ID name for a div. 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. This might be very obvious for some people with more experience.

0

精彩评论

暂无评论...
验证码 换一张
取 消