我有以下的html代碼。它由Razor引擎生成。這是動態的。我的意思是,下拉的元素不會因用戶而異。我需要將此下拉列表複製到同一個下拉列表中,並使用新的ID和新名稱。我看了here,here,here和here。以下是我的html。我已在代碼中添加註釋以獲得更多說明。如何更新div元素中html元素的id和名稱?
<!-- the entire section with id and name template needs to be copied -->
<div id="template" name="template" class="form-group unique">
<label class="control-label col-md-2" for="Course">Course</label>
<!-- the drop down below has id and name as Course[0].Title
I need to increment index inside [] -->
<div class="col-md-10">
<select class="form-control drop valid" id="Course[0].Title" name="Course[0].Title">
<option value="1">Statistics</option>
<option value="2">Trigonometry</option>
<option value="3">Biology</option>
<option value="4">Neurology</option>
<option value="5">Applied</option>
<option value="6">Theoretical</option>
</select>
</div>
</div>
現在,我想出了下面的jQuery代碼。它只複製一次,然後停止工作。我檢查了控制檯,沒有錯誤。帶有澄清意見的JavaScript代碼如下。
< script src = "~/Scripts/jquery-1.10.2.min.js" > < /script>
<script type="text/javascript
">
$(document).ready(function() {
\t //copy the section with class name unique
var clone = $('.unique').clone();
\t //Copy again as i am modifying the id,name of div with unique class
var clone2 = $('.unique').clone();
\t //initialize the index with 1, the item with 0 index is already in webpage.
var i = 1;
\t //Change name of drop down who has class drop and assign new name
$(".unique ").find(".drop ").attr("
name ", "
Course[0].Title ");
\t //Change id of drop down who has class drop and assign new id
$(".unique ").find(".drop ").attr("
id ", "
Course[0].Title ");
\t //on click of plus button, i add clone of drop down with parent div section and with new id and name
$("#
plus ").click(function() {
\t //Add after the element which has class unique
$('.unique').after(clone2);
\t //Find name inside unique and update
$(".unique ").find(".drop ").attr("
name ", "
Course[" + i + "].Title ");
\t //Find id inside unique and update
$(".unique ").find(".drop ").attr("
id ", "
Course[" + i + "].Title ");
\t //Increment the index
i = i + 1;
});
});
</script>
哪些錯誤的腳本?
This Works。我沒有在我的控制器中獲得價值。可能還有更多東西要查找。我正在查。一旦我完成,我會接受答案。感謝努力。 –
不客氣。我還更改了在代碼中克隆的'.unique'類的attr'id'和'name',因爲ID必須是唯一的。 –
是的。我注意到了。這十分完美。 –