【问题标题】:Passing a variable from a Select Value to a document.querySelectorAll(Variable here)将变量从选择值传递到 document.querySelectorAll(此处为变量)
【发布时间】:2020-06-03 19:18:45
【问题描述】:

我希望能够从 HTML 页面上的选择器下拉列表中选择一个值,并将“值”传递给 .js 页面上的 document.querySelectorAll()。尝试了许多不同的变化,它只是没有发生。

<div class="custom-select">
     <select id="selected" onchange="changeKey()">
            <option value="0">Select Key:</option>
            <option value="aminorpenta">A</option>
     </select>
</div>




Var aminorpenta = [".ANat",".CNat",".DNat",".ENat",".GNat"];

function changeKey() {
 var elements = document.querySelectorAll(variable goes here), i;
 for (i = 0; i < elements.length; ++i) {
 elements[i].style.backgroundColor = "yellow";
 elements[i].style.color = "black";
alert(dayVal);
 }
}

【问题讨论】:

  • dayVal 是什么?我没有看到它在其他任何地方使用过。另外,您打算选择多项还是只选择一项?
  • 你可以stringifyaminorpenta的内容。假设 每个 选项都有一个遵循相同约定的属性,您可以解析所选选项的属性。这和你想做的一样吗?
  • 如果我直接在 document.querySelectorAll(variable here) 中使用变量,它会按需要工作。
  • @MihailMinkov 对此感到抱歉,dayVal 的剩菜来自不同的尝试。是的,会有多个选择/变量,总共 12 个。
  • 所以为了清楚起见,您有 12 个 select 元素,您想使用带有字符串的数组来更新它们的选项?

标签: javascript variables selector


【解决方案1】:

使用标准 Javascript 对象表示法中的值映射。 您可以使用方括号表示法使用动态键从对象中检索值。

const myObject = {
    aminorpenta: [".ANat",".CNat",".DNat",".ENat",".GNat"],
    //  more key: value pairs
}
function changeKey() {
    const selectElement = document.getElementById("selected");
    const selectedValue = selectElement.options[selectElement.selectedIndex].value;
    const elements = document.querySelectorAll(myObject[selectedValue])
    for (i = 0; i < elements.length; ++i) {
        elements[i].style.backgroundColor = "yellow";
        elements[i].style.color = "black";
    }
}

已编辑。

【讨论】:

  • 非常欢迎!我能麻烦您接受答案吗...?
猜你喜欢
  • 2018-05-20
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多