我有一个下拉列表,其中包含开始时间和结束时间。我的页面上也显示了“已预订”的时间。我正在尝试创建一个函数来查看是否有任何“预订”值与下拉列表值匹配,如果是,则将它们从数组中删除。我无法弄清楚如何设计我的 JavaScript 函数来执行此操作,非常感谢这方面的任何帮助。
删除.js
$(function () {
var removeItem = document.getElementsByClassName('set');
$('#time').find('option[value=="' + removeItem + '"]').remove();
});
时间.js
var start = document.getElementById('start').innerHTML.split('.').join('').toLocaleLowerCase();
var end = document.getElementById('end').innerHTML.split('.').join('').toLocaleLowerCase();
var time = document.getElementById('time');
time.disabled = true;
var slotTimes = [];
document.getElementById("length").onchange = function (evt) {
var timeDistance = evt.target.value;
var startMoment = moment(start, "h:mm a");
var endMoment = moment(end, "h:mm a");
slotTimes = [];
while (startMoment.isSameOrBefore(endMoment)) {
slotTimes.push(startMoment.format("h:mm a"));
startMoment = startMoment.add(timeDistance, 'minutes');
}
addDropdown();
disabled();
};
function disabled(option) {
if (option != "") {
time.disabled = false;
}
}
function addDropdown() {
var doc = '',
times = slotTimes,
i;
for (i = 0; i < times.length; i++) {
doc += "<option value='" + times[i] + "'>" + times[i] + "</option>";
}
document.getElementById('time').innerHTML = doc;
disabled();
}
最佳答案
首先,您应该使用 jQuery!
$('#foo')
与 document.getElementById('foo')
相同
$('.bar')
与 document.getElementByClassName('bar')
相同
现在要解决您的问题,您正在尝试放置一个 html 元素
即 document.getElementByClassName('set')
代替一个值。尝试运行 console.log(removeItem)
,您会明白我的意思。
我想你正在尝试做的是:
$(document).ready(function() {
$('.set').each(function() { //loop over all elements with a class == 'set'
const removeItem = $(this).val(); //get value of each element
$('#time').find('option=[value=="' + removeItem + '"]').remove();
});
});
如果您需要更多帮助,请告诉我。
希望这对您有所帮助!
更新
您应该将 removeItem
循环放在 addDropdown
函数的末尾:
function addDropdown() {
var doc = '',
times = slotTimes,
i;
for (i = 0; i < times.length; i++) {
doc += "<option value='" + times[i] + "'>" + times[i] + "</option>";
}
document.getElementById('time').innerHTML = doc;
disabled();
$('.set').each(function() { //loop over all elements with a class == 'set'
const removeItem = $(this).val(); //get value of each element
$('#time').find('option=[value=="' + removeItem + '"]').remove();
});
}
更新2
我建议重写您的代码以使用 selectpicker Bootstrap 包。看起来你试图制作的大多数“功能”都有简单的关键字 selectpicker用途。
例如,要禁用此下拉列表中的选项:
<select class="selectpicker" id="toppings">
<option id="opt_1">Mustard</option>
<option id="opt_2">Ketchup</option>
<option id="opt_3">Relish</option>
</select>
你只需要做:
$('#opt_2').prop('disabled', true);
如果您需要通过它们的父级 下拉列表来引用特定的特定选项,您可以使用children方法:
$('#toppings').children('.someClass').prop('disabled', true);
这会将 toppings
下拉列表中具有 class="someClass"
的所有选项更改为禁用。
我相信 selectpicker 包中有几个功能,您以后也会发现它们很有用!
我不确定您的代码具体有什么问题,但它看起来越来越像您可以免费使用的 selectpicker 包。
关于javascript - 从动态生成的下拉列表中删除时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55193039/