我有这一段代码,它从几个类似的循环中获取数据,并返回用户选择的下拉列表的 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;
};
我不知道它是否相关,但有问题的脚本设置为每秒刷新大约五次,以便为用户提供近乎实时的反馈。我的控制台日志没有做任何让我相信这是我的问题的原因的事情。
最佳答案
您的代码:
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);
}
关于javascript 生成的 <option> 标签从 feeder 函数获取错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31956053/