![](/img/trans.png)
[英]Pass to javascript variable attribute from html input id=“attribute”
[英]add id attribute to html input
我通過按鈕動態插入新的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文本就會消失。
我知道輸入內容從技術上來說還是個孩子...
沒什么“技術上的”,只是個孩子。 不過,您仍然可以設置其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");
(和下一個塊類似。)在那里,在創建結構之后,我使用.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()
。
那是因為鏈接的順序。 如果在將屬性附加到DOM之前找到並添加屬性,則最終只會添加輸入(由於查找)。
只需追加元素,然后更改您的id即可:
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Return :</h4><label><span>Return :</span><input type='text' value='' /></label>")
.insertBefore("#elementtarget")
.find('input')
.attr("id", "targetreturn" + counter);
如何在HTML字符串上設置ID?
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Return :</h4><label><span>Return :</span><input type='text' value='' id='targetreturn" + counter + "'/></label>")
.insertBefore("#elementtarget");
PS:記得在提交之前先解析輸入字段; 否則您將無法獲取數據...或在輸入字段上也設置“名稱”:p
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.