我有这个 JavaScript 函数(如下),它将动态地将新元素添加到 DOM(没问题)除了没有添加名称属性或 ID 值。
我希望实现的最终目标是能够动态地将元素添加到流程中,然后能够保存它(通过 jQuery 序列化提交),而无需刷新页面(简单来说,可以考虑添加/删除项目的任务)。动态“添加”是我正在努力解决的问题。
这是我迄今为止的精简代码:
<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>
这是我当前在单击“添加新任务”两次时获得的输出源:
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>
这是查看源代码时所需的输出:
<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>
有人可以帮我修改我的函数以增加新添加的 DOM 元素吗?
最佳答案
您可以考虑更新函数以查看当前有多少元素(通过 getElementsByClassName()
函数),并使用它分别设置 id
和 name
属性创建新元素时:
<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>
您可以see a working example here输出标记的示例如下:
关于javascript - 使用 jQuery 将新元素(动态)添加到 dom 时缺少 name 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36720595/