我遇到了两个问题:第一个是 javascript 没有向菜单添加选项,第二个是我的 for 循环结束时出现“意外或无效令牌”错误。
更新: 令牌错误是一个奇怪的字符。我删除了导致问题的行并重新输入,现在我不再收到错误,但我的脚本仍然没有添加选项。
我已阅读有关向选择菜单添加选项的信息,但我在那里找到的答案对我不起作用。我应该指出这是 Joomla 网站 (v3.8) 的一部分,因为这可能会导致一些意外行为。
我有一个函数,它应该根据字符串“id”挑选出一个特定的选择菜单,清除它的内容,然后用“options”数组的元素重新填充它。
function resetSelectMenu(id, options){
// Selects the correct menu, enables it, and removes all of its options.
var selectMenu = jQuery('#sel-' + id);
selectMenu.prop('disabled', false);
selectMenu.empty();
// Makes an option element and sets its text and value.
var el = document.createElement("option");
el.text = 'blah';
el.value = 'blah';
// Does not succeed in adding an option to menu.
selectMenu.add(el);
// I declared loop variables here to make sure there are no re-declaration issues.
var i;
var opt;
// The loop is entered and the array is iterated through.
for(i = 0; i < options.length; i++){
opt = options[i];
el = document.createElement("option");
el.text = opt;
el.value = i + 1;
// Does not succeed in adding an option to menu.
selectMenu.add(el);
}
}
该函数确实针对正确的菜单并清除其内容,但它没有添加“blah”选项或“options”数组中的任何内容。我尝试使用“appendChild(el)”而不是 add,但出现“appendChild() 不是函数”形式的错误。我做了很多控制台日志来确定代码的所有部分都按预期工作,除了“selectMenu.add(el);”