我通过按钮动态插入新的 html 文本输入,但是当我创建它们并分配 ID 时,它会将 ID 分配给 H4 文本和标签,而不是实际的输入元素。我正在使用 Jquery 创建元素..
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Name :</h4><label><span>Name :</span><input type='text' value='' /></label>")
.attr("id", "targetname" + counter)
.insertBefore("#elementtarget");
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Return :</h4><label><span>Return :</span><input type='text' value='' /></label>")
.attr("id", "targetreturn" + counter)
.insertBefore("#elementtarget");
我知道输入在技术上是一个子项,但如果我尝试设置子项的属性,H4 文本就会消失。
最佳答案
I know that the input is technically a child...
没有什么“技术性”,它只是一个 child 。不过,您仍然可以设置其 id
:
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Name :</h4><label><span>Name :</span><input type='text' value='' /></label>")
.find("input").attr("id", "targetname" + counter).end()
.insertBefore("#elementtarget");
(下一个 block 也类似。)创建结构后,我使用 .find("input")
查找其中的 input
,然后分配id
,然后使用end
,这样我们就可以回到原始的jQuery对象(h4
及其后代),这样我们就可以使用 >insertBefore
就可以了。
或者,您可以在插入结构后添加id
:
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Name :</h4><label><span>Name :</span><input type='text' value='' /></label>")
.insertBefore("#elementtarget")
.find("input").attr("id", "targetname" + counter);
...这意味着您不再需要end()
。
关于javascript - 将 id 属性添加到 html 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24740441/