Javascript - 向ID和Class添加增量编号

时间:2018-03-19 08:26:16

标签: javascript forms input

我正在尝试将ID和类添加到输入字段以及在每个ID和类元素之后添加一个数字,以便它们都具有唯一的ID和类别。我需要将它添加到窗口加载的输入字段中。经过多次尝试,我无法通过各种反建议来做到这一点。

我现在已经删除了非工作代码以显示我的起点,并希望有人可以给我额外的JavaScript来做到这一点:),到目前为止我所拥有的是

Name: <input  placeholder="Please provide your name" class="form-control ng-pristine ng-empty ng-valid ng-valid-required ng-touched" style="">
Phone: <input  placeholder="Please provide your phone number" class="form-control ng-pristine ng-empty ng-valid ng-valid-required ng-touched" style="">
<button>A button</button>
<script>
  function myFunc() {
  document.getElementsByTagName("input")[0].setAttribute("id", "fieldid");
  document.getElementById("fieldid").value = "Johnny Bravo";
  var element = document.getElementById("fieldid");
  element.classList.add("mystyle");
}
window.onload = myFunc;

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

var elements = document.getElementsByTagName('input');

var index = 1;
for(var e of elements){
    e.setAttribute("id", "fieldid"+index);
    index++;
}

您可以对class属性执行相同操作。当然,如果您不希望页面上的每个输入元素都获得新ID,则必须使用更具体的选择器。

答案 1 :(得分:0)

以下示例说明如何使用idclass元素的inputfunction myFunc() { var inputElem = document.getElementsByTagName("input"); for(var i=0; i < inputElem.length; i++){ inputElem[i].setAttribute("id", "field"+i); inputElem[i].value = "Johnny Bravo "+i; inputElem[i].classList.add("mystyle" + i); } } window.onload = myFunc();名称的增量值:

&#13;
&#13;
Name1: <input  placeholder="Please provide your name" class="form-control ng-pristine ng-empty ng-valid ng-valid-required ng-touched" style="">
Phone1: <input  placeholder="Please provide your phone number" class="form-control ng-pristine ng-empty ng-valid ng-valid-required ng-touched" style="">
Name2: <input  placeholder="Please provide your name" class="form-control ng-pristine ng-empty ng-valid ng-valid-required ng-touched" style="">
Phone2: <input  placeholder="Please provide your phone number" class="form-control ng-pristine ng-empty ng-valid ng-valid-required ng-touched" style="">
Name3: <input  placeholder="Please provide your name" class="form-control ng-pristine ng-empty ng-valid ng-valid-required ng-touched" style="">
Phone3: <input  placeholder="Please provide your phone number" class="form-control ng-pristine ng-empty ng-valid ng-valid-required ng-touched" style="">
<button>A button</button>
&#13;
    SELECT a.country1,  b.c2 as Country2
    FROM test1  a 
    cross join 
    (SELECT country2 as c2
     FROM test1) as b
&#13;
&#13;
&#13;