這裏重複代碼是我的提琴:添加新的選項,以排除和事件類別選擇DEMO優化添加新的選項來選擇jQuery的
我已經重複碼。我如何優化相同的消除重複的代碼?
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
對不起,我可能已經更新了你的小提琴 - 我沒想到它會更新實際小提琴本身。我會恢復到舊版本。只是檢查,沒有它沒有更新實際的小提琴。 – Yatin