简体   繁体   English

使用jQuery将新元素动态添加到dom时缺少name属性

[英]name attribute missing when adding new element to dom (dynamically) using jQuery

I have this JavaScript function (below) that will dynamically add a new element to the DOM (no problem) except there is no name attribute added or ID value. 我有这个JavaScript函数(如下),它将动态向DOM中添加一个新元素(没有问题), 除非没有添加名称属性或ID值。

The ultimate goal I'm looking to achieve is to be able to dynamically add elements to a process and then be able to save it (submit via jQuery serialize) without a page refresh (in simple terms, think of adding/removing tasks to a project). 我要实现的最终目标是能够动态地向流程中添加元素,然后能够在不刷新页面的情况下保存它(通过jQuery序列化提交)(简单来说,可以考虑将任务添加/删除)。项目)。 Dynamically "adding" is what I'm struggling with. 我一直在努力地动态地“添加”。

Here is the stripped down code I have so far: 这是我到目前为止的精简代码:

<div id="itemList">
    <div><input class="textInput" name="input_1"  id="input_1" type="text" /></div>
    <div><input class="textInput" name="input_2"  id="input_2" type="text" /></div>
    <div><input class="textInput" name="input_3"  id="input_3" type="text" /></div>
</div>
<div><a href="javascript:void('');" id="addNewInputField" onClick="addNewInputField();">Add New Task</a></div>

<script type="text/javascript">
function addNewInputField(){
    elParentContainer = document.getElementById('itemList');
    newElement = document.createElement('div');
    newInput = document.createElement('input');
    newInput.setAttribute('class', 'textInput');
    newInput.setAttribute('type', 'text');      
    newElement.appendChild(newInput);
    elParentContainer.appendChild(newElement);
}
</script>

and here is the outputted source I'm currently getting when clicking the "Add New Task" twice: 这是我两次单击“添加新任务”时当前获得的输出源:

Here is the what I'm currently getting when you view source:

<div id="itemList">
    <div><input class="textInput" name="input_1" id="input_1" type="text"></div>
    <div><input class="textInput" name="input_2" id="input_2" type="text"></div>
    <div><input class="textInput" name="input_3" id="input_3" type="text"></div>
    <div><input class="textInput" type="text"></div>
    <div><input class="textInput" type="text"></div>
</div>

Here is the desired output when you view source: 查看源时,这是所需的输出:

<div id="itemList">
    <div><input class="textInput" name="input_1" id="input_1" type="text"></div>
    <div><input class="textInput" name="input_2" id="input_2" type="text"></div>
    <div><input class="textInput" name="input_3" id="input_3" type="text"></div>
    <div><input class="textInput" name="input_4" id="input_4" type="text"></div>
    <div><input class="textInput" name="input_5" id="input_5" type="text"></div>
</div>

Can someone help me modify my function to increment the newly added DOM elements? 有人可以帮助我修改功能以增加新添加的DOM元素吗?

You could consider updating your function to see how many current elements there are (via the getElementsByClassName() function) and use that to set your id and name properties respectively when creating your new element : 您可以考虑更新函数,以查看有多少当前元素(通过getElementsByClassName()函数),并在创建新元素时分别使用它们来设置idname属性:

<script type="text/javascript">
  function addNewInputField(){
      // Set how many elements you have with that class (to determine which
      // value to append to 'input_{x}'
      var currentInput = document.getElementsByClassName('textInput').length + 1;
      elParentContainer = document.getElementById('itemList');
      newElement = document.createElement('div');
      newInput = document.createElement('input');
      newInput.setAttribute('class', 'textInput');
      // Set your new ID attribute
      newInput.setAttribute('id', 'input_' + currentInput);
      // Set your new name attribute
      newInput.setAttribute('name', 'input_' + currentInput); 
      newInput.setAttribute('type', 'text');      
      newElement.appendChild(newInput);
      elParentContainer.appendChild(newElement);
  }
</script>

You can see a working example here and an example of what the output markup would look like below : 您可以在此处看到一个工作示例,以及以下输出标记示例:

在此处输入图片说明

Based on your stripped down version, you could keep track of how many inputs you have and update them with each new addition. 根据精简后的版本,您可以跟踪有多少输入,并在每次添加新输入时进行更新。 Here is a solution based on the code you submitted. 这是基于您提交的代码的解决方案。

   <div id="itemList">
<div><input class="textInput" name="input_1"  id="input_1" type="text" /></div>
<div><input class="textInput" name="input_2"  id="input_2" type="text" /></div>
<div><input class="textInput" name="input_3"  id="input_3" type="text" /></div>

    <div><a href="javascript:void('');" id="addNewInputField" onClick="addNewInputField();">Add New Task</a></div>

    <script type="text/javascript">
     var inputCounter =  3;
     function addNewInputField(){
        var name = "input_";
        inputCounter= inputCounter+1;
        name = name.concat(inputCounter);
        elParentContainer = document.getElementById('itemList');
        newElement = document.createElement('div');
        newInput = document.createElement('input');
        newInput.setAttribute('class', 'textInput');
        newInput.setAttribute('type', 'text');
        newInput.setAttribute('name', name);
        newInput.setAttribute('id', name);      
        newElement.appendChild(newInput);
        elParentContainer.appendChild(newElement);
}
</script>

If you want to use jQuery please consider using code like this : 如果你想使用jQuery,请考虑使用类似的代码这样

  var inputCount = $('.textInput').size();
  inputCount += 1;
  $('#itemList').append('<div><input class="textInput" name="input_'+inputCount+'" id="input_'+inputCount+'" type="text" /></div>');

Additionally it may be more appropiate to use the data attribute, you might consider it. 此外,使用data属性可能更合适,您可以考虑一下。

You can just count how many children your container has and then create dynamically the id and name of the next element. 您可以只计算容器有多少个子代,然后动态创建下一个元素的ID和名称。

function addNewInputField(){
elParentContainer = document.getElementById('itemList');
var next_input = elParentContainer.children.length+1
newElement = document.createElement('div');
newInput = document.createElement('input');
newInput.setAttribute('class', 'textInput');
newInput.setAttribute('type', 'text');      
newInput.setAttribute('name', 'input_'+next_input);      
newInput.setAttribute('id', 'input_'+next_input);   
newElement.appendChild(newInput);
elParentContainer.appendChild(newElement);

} }

You could keep track of the current number of inputs you have.That way it becomes easier to set the desired attributes of new inputs as you create them. 您可以跟踪当前拥有的输入数量,这样可以在创建新输入时轻松设置所需的属性。

     <script type="text/javascript">
        var inputCounter =  3;
     function addNewInputField(){
        var name = "input_";
        inputCounter= inputCounter+1;
        name = name.concat(inputCounter);
        elParentContainer = document.getElementById('itemList');
        newElement = document.createElement('div');
        newInput = document.createElement('input');
        newInput.setAttribute('class', 'textInput');
        newInput.setAttribute('type', 'text');
        newInput.setAttribute('name', name);
        newInput.setAttribute('id', name);      
        newElement.appendChild(newInput);
        elParentContainer.appendChild(newElement);
    }

   </script>

One way to achieve this is to retrieve the last child of the collection, then use one of it's attributes to know the current index. 实现此目的的一种方法是检索集合的最后一个子项,然后使用其属性之一来了解当前索引。 Once this has been retrieved, it's easy to add attributes with the right contents to the newly created element: 一旦检索到该属性,就可以将具有正确内容的属性添加到新创建的元素中:

function addNewInputField(){
    var elParentContainer = document.getElementById('itemList');

    //Get last child of list
    var inputList = elParentContainer.getElementsByTagName('input');
    var lastChild = inputList[inputList.length-1];

    //Get last index from the name attribute of last child
    var lastIndex = lastChild.getAttribute('name').split('_')[1];

    var newElement = document.createElement('div');
    var newInput = document.createElement('input');
    newInput.setAttribute('class', 'textInput');
    newInput.setAttribute('type', 'text');
    //Add new attributes to the newly created element
    newInput.setAttribute('name', 'input_'+(lastIndex++));
    newInput.setAttribute('id', 'input_'+(lastIndex++));   
    newElement.appendChild(newInput);
    elParentContainer.appendChild(newElement);
}

Have you tried Jquery.append() functionality. 您是否尝试过Jquery.append()功能。

Hope this will solve your problem, where you can use to create dynamic elements and also append any text in the page. 希望这可以解决您的问题,您可以在其中使用它来创建动态元素,还可以在页面中添加任何文本。

Please see the sample and try this link , you will get better idea. 请查看示例并尝试使用此链接,您将获得更好的主意。

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_append_ref http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_append_ref

Let me know, if any more support needed. 让我知道,是否需要更多支持。

Thanks, Bhuvan 谢谢,布凡

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

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