使用javascript为输入元素设置动态独特的id属性 [英] Setting dynamically distinct id attribute using javascript for input element

查看:134
本文介绍了使用javascript为输入元素设置动态独特的id属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为表中动态添加的输入框设置不同的ID时遇到问题. 问题是:

I am facing a problem in setting distinct ids for dynamically added input boxes in a table. The problem is:

当用户单击添加新行"时,我正在插入新行.现在,我必须为输入框设置不同的ID.每当用户单击添加新行"按钮时,我都会使用一个静态变量并增加其值.然后我将其值附加到id值上,例如temp(即id将为temp1temp2等).我将变量xyz作为 var xyz = "temp" + i(其中i是计数器) 现在我必须使用setattributexyz分配给ID. 但是由于setattribute中的值只能是文字,因此如何使用变量代替值?

I am inserting new rows when the user clicks on "Add new Row". Now I have to set distinct id for the input box. I have taken a static variable and increasing its value every time user clicks on add new row button. Then I am appending its value to id value lets say temp (i.e. ids will be temp1, temp2 and so on). I have taken a variable xyz as var xyz = "temp" + i (where i is the counter) and now I have to assign xyz to the id using setattribute. But as values in setattribute can only be literals, how can I use a variable in place of the value?

如果您有其他方法,请告诉我.

If you have any other methods, please let me know.

推荐答案

它也可以是一个包含字符串的变量.

It can be a variable which holds a string as well.

var fooId = "foo";
for (var i = 0; i <= 2; i++) {
    document.getElementsByTagName('div')[i].setAttribute('id', fooId + (i + 1));
}

实时演示

Live DEMO

这篇关于使用javascript为输入元素设置动态独特的id属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆