【问题标题】:How to load dropdown menu from Obj如何从 Obj 加载下拉菜单
【发布时间】:2021-04-06 16:17:48
【问题描述】:

我是 JS 新手,我想就如何使用 Javascript 和我在下面定义的对象加载页面 DOM 后如何填充下拉菜单寻求指导。我在这里和其他地方看了几个例子;但是,我仍然不清楚如何做到这一点。在下面的代码中,我不太明白我应该在 opt.innerHTML 中包含什么?是带有指向对象的变量的 ul li 元素吗?感谢您对此的任何帮助。

const score = document.querySelector('#score');

const output = document.querySelector('#output');

const answerSelect = document.querySelector('#selAnswers');

const categorgySelect = {
    
    Category: 'Sports',
    Category: 'Art',
    Category: 'Vehicles',
    Category: 'History',

};

const difficultySelect = {
    
    Difficulty: 'easy',
    Difficulty: 'medium',
    Difficulty: 'hard',
    

};

let categoryPick = document.querySelector('#category');

document.addEventListener('DOMContentLoaded', function() {
         for(let index in categorySelect) {
            let opt = document.createElement('option');
            opt.value = categorySelect;
            opt.innerHTML = ???

            categorySelect.appendChild(opt);
         }
});



<!doctype html>
<html lang="en">
<head>
    <title>l</title>
    <link rel='stylesheet' href='css/Trivia.css' >
</head>
<body>
    <h1>Trivia</h1>
    <div>Score: <span id="score">Correct 0 Wrong 0</span></div>
    <br>
    <div> 
        <label>Select Category:</label>
        <select id='category'></select>
        <br> 
        <label>Select Difficulty:</label>
        <select id='difficulty'></select>
    </div>
    <br><br>
    <div id="output"></div>
    <br>
    <div id="selAnswers"></div>
    <br>`enter code here`
    <button id="btn">Get First Question!</button>
    <script src ='js/Trivia.js'></script>
</body>
</html>

【问题讨论】:

    标签: javascript html json object


    【解决方案1】:

    你的对象应该有唯一的键。

    尝试使用数组而不是对象。

    const categorgySelect = [ 'Sports', 'Art', 'Vehicles', 'History' ];
    const difficultySelect = [ 'easy', 'medium', 'hard' ];
    

    像这样更新你的 For 循环,

    let opt = document.createElement('option');
    opt.value = categorySelect[index];
    opt.innerHTML = categorySelect[index];
    categoryPick.appendChild(opt)
    

    你必须追加到select

    参考:

    对象:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

    数组:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

    【讨论】:

    • 感谢您的回复。我可能已经提到我将把它连接到一个简单的 API 以生成问题,这些问题以我在对象中列出的相同方式存储类别,不确定这是否会改变事情?
    【解决方案2】:

    首先,const categorgySelect 中的拼写错误:您的意思可能是 categorySelect
    此外,“select”在这里并不适合命名,最好直接称它为categoriesdifficultySelect 也一样。

    您正在为一个属性分配多个值:

    const categorgySelect = {
      Category: 'Sports',
      Category: 'Art',
      // ...
      Category: 'History'
    };
    

    这将覆盖任何先前定义的值,这意味着对象将只保存该属性的最后一个值(此处为:Category: 'History')。

    要保存一个值数组,请使用Array
    注意不同的括号[],因为我们现在使用数组字面量创建一个数组,并且不是使用对象字面量的对象。

    const categorgySelect = [
      'Sports',
      'Art',
      // ...
      'History'
    ];
    

    同样适用于difficultySelect

    现在在DOMContentLoaded 监听器中,我们想用&lt;option&gt;s 填充&lt;select&gt;s。这可以使用for...of-loop 轻松完成。
    注意:for...of-循环遍历对象的可迭代属性,而 @ 987654323@ 循环遍历对象的 可枚举 属性(MDN 详细介绍了 differences between for...of and for...in)。对于数组,它们可能看起来相似,但完全不同。通常,需要一个 for...of 循环,但始终尝试考虑要循环的内容。

    我们可以使用Element.innerHTML(最好使用预构建的字符串)或Element.append() 将选项添加到选择元素。

    以下是使用上述两种方法填充的两个选择:

    const categories = [ // Fixed name
      'Sports',
      'Art',
      'Vehicles',
      'History'
    ];
    
    const difficulties = [ // Better name
      'easy',
      'medium',
      'hard'
    ];
    
    document.addEventListener('DOMContentLoaded', function() {
      // Moved inside listener to free up namespace
      let categorySelect = document.querySelector('#category');
      let difficultySelect = document.querySelector('#difficulty');
    
      let html = '';
      for (let item of categories) {
        // Appending Strings created using Template literals
        html += `<option>${item}</option>`;
      }
      categorySelect.innerHTML = html;
      
      for (let item of difficulties) {
        let opt = document.createElement('option');
        
        // <option> will use its .textContent as value if not explicitly defined
        opt.textContent = item;
        
        difficultySelect.append(opt);
      }
    });
    label {display: block}
    <!-- Placed <select>-tags inside <label>-tags due to accessibility reasons -->
    
    <label>Select Category:
      <select id='category'></select>
    </label>
    <label>Select Difficulty:
      <select id='difficulty'></select>
    </label>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多