我有2個函數用於創建一個新的select元素,並在表格中有各種選項。選項的數量是可變的,並將通過一個數組傳遞。問題是,我無法通過單擊添加新鏈接來使兩個函數都能正常工作。我已經探索了許多不同的方法,但是因爲HTML在表格中,我很難在表格中添加一行,創建新的選擇並同時添加選項。謝謝,如果你能幫助。從1點擊表格內添加選擇和選項
我一直在這個環節上測試代碼:http://jsfiddle.net/DegTc/30/
$(function() {
$(".AddItem").click(function() {
$(this).closest('table').find('tr:last').prev().after('<tr><td><select type="select" class="custom-select custom-select_gray" data-toggle="dropdown" id="dropdownMenuAdded" aria-haspopup="true" aria-expanded="true" style="font-family: \'Work Sans\', Tahoma, Geneva, sans-serif;font-size:10px;color:#606060;text-align:center;width:100px;height:25px;"><option label="Event">Event</option></select></td></tr>');
return false;
});
});
$(function() {
$(".AddOption").click(function() {
var events = [[ "Event 1", "10.04"], [ "Event 2", "30.04"]];
var selId = "dropdownMenuAdded";
initDropdownList(selId, events);
function initDropdownList(id, eventEls) {
var select, i, option;
select = document.getElementById(id);
for (i = 0; i < eventEls.length; i++) {
option = document.createElement('option');
/* alert("eventEls.length: " + eventEls.length);
alert("eventEls[i]: " + eventEls[i][0] + " " + eventEls[i][1]);*/
option.value = option.text = eventEls[i][0] + " " + eventEls[i][1];
select.add(option);
}
select.id = "dropdownMenu1";
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>
<select type="select" class="custom-select custom-select_gray" style="font-family:Work Sans, Tahoma, Geneva, sans-serif;font-size:10px;color:#606060;text-align:center;width:100px;height:25px;">
<option label="Event">Event</option>
</select>
</td>
</tr>
<tr><td><select type="select" class="custom-select custom-select_gray" data-toggle="dropdown" id="dropdownMenu1" aria-haspopup="true" aria-expanded="true" style="font-family:Work Sans, Tahoma, Geneva, sans-serif;font-size:10px;color:#606060;text-align:center;width:100px;height:25px;"><option label="Event">Event</option></select></td></tr>
<tr>
<td><a href="javascript:void(0);" id="AddNew" class="AddItem"><i class="i-plus"></i>Add new</a>
</td>
<td><a href="javascript:void(0);" id="AddNew" class="AddOption"><i class="i-plus"></i>Add Options</a>
</td>
</tr>
</table>
謝謝,這兩個答案的問題解決了,但我真的沒有考慮ID是相同的,當我創造了它。 – Matts