我有这段代码,它从几个类似的循环中获取数据,并返回用户选择的下拉列表的id。问题是填充在给定标记中的id(或值或数据)是不可预测的,但总是错误的。
inputModeSelect();
if(inputUnits.value != "default" && outputUnits.value != "default")
{
var input = inputUnits.options[inputUnits.selectedIndex].id;
var output = outputUnits.options[outputUnits.selectedIndex].id;
console.log(input);
console.log(output);
生成列表的函数基本相同,并遵循此模式。 inputArray,inputUnits和conversionFactor来自一个允许用户在几个不同测量类别之间进行选择的函数,并且都正确填充。
" inputUnits"是此循环处理的标记的名称。
function inputHandler(inputArray, inputUnits, conversionFactor)
{
/* This is the same value as is passed by inputUnits unless the
user updates the mode selector on the page. */
var inputUnitsArray = [];
inputUnitsArray = document.getElementById("inputUnits");
//these are returning the values I expect
console.log(inputUnitsArray);
console.log(inputArray);
console.log(conversionFactor);
/* This section is where my problem seems to be. I test how many
options there are in the "inputUnits" <select> tag, and compare that
to the length of the array used to populate the list. This works, and
correctly calls my "for" loop, but where I expect it to populate the
option.innerHTML, option.value, option.dataset, and option.id tags
consistantly in accordance with the passed arrays, I am getting strange
behavior. Most recently a tag which was called "milligrams" in the
select menu returned "ounces" as it's .value attribute. I'm not sure how
I can be populating those values in a single iteration from a single
source value and return different strings. */
if (inputUnitsArray.length < inputArray.length + 1)
for(i = 0; i < inputArray.length; i++)
{
var option = document.createElement("option");
option.innerHTML = "<option>"+(inputArray[i])+"</option>";
option.value = inputArray[i];
option.dataset.conversionFactor = conversionFactor[i];
option.id = inputArray[i];
document.getElementById("inputUnits").appendChild(option);
}
/* tests the value attribute of the first custom object against the
array generated by the feeder function, and removes everything but the
default object when they don't match. This section is working correctly.
*/
if(inputUnitsArray[1].value != inputArray[0])
{
for (i = inputUnitsArray.length; i > 1; i--)
{
inputUnits.removeChild(inputUnits.lastChild);
}
};
ctx.clearRect(0, 0, canvas.width, canvas.height);
return;
};
我不知道它是否相关,但有问题的脚本设置为每秒刷新大约五次,以便为用户提供近乎实时的反馈。我的控制台记录不会做任何让我相信这是我的问题的原因。
答案 0 :(得分:1)
您的代码:
option.innerHTML = "<option>"+(inputArray[i])+"</option>";
在option
元素中嵌套option
元素。这足以使用:
option.innerHTML = inputArray[i];
创建选项的部分和工作示例:
<select id='inputUnits'> </select>
var inputArray = ['1', '2', '3']
for(i = 0; i < inputArray.length; i++) {
var option = document.createElement("option");
option.innerHTML = inputArray[i];
option.value = inputArray[i];
option.id = inputArray[i];
document.getElementById("inputUnits").appendChild(option);
}