首页 > 解决方案 > 基本,通过从另一个选择中选择选择选项

问题描述

</head>
      <body>
         <fieldset>
                <legend>D'où venez-vous ?</legend>
             <div>Pays:
            <select id="pays">
                    <option value="1">Canada</option>       
                    <option value="1">France</option>       
            </select>       

        </div>
              <div>Ville:<select id="ville"onclick="myFunction()"> 
 </select>   
           </div>

             </fieldset>
          </body>
     </html>

基本上,我想要做的是在我的第二个选择上添加一个名为“ville”的选项,当我选择加拿大时,它会给我另一个选择中的 3 个城市,反之亦然。我不知道如何做这个练习。谢谢。我应该使用for,还是仅在其他条件可行的情况下使用。

标签: javascript

解决方案


这将是一个解决方案:

// Setting variables which cannot be redeclared
const pays = document.getElementById('pays');
const france = ['Paris', 'Lyon', 'Marseille'];
const canada = ['Toronto', 'Vancouver', 'Victoria'];

// If select element (#pays) changes
pays.addEventListener('change', () => {
  // France
  if (pays.value === 'France') {
    createElement(france);
  }
  // Canada
  else if (pays.value === 'Canada') {
    createElement(canada);
  }
});

// Create option elements
function createElement(country) {
  const ville = document.getElementById('ville');
  // Delete all values before adding new ones
  ville.innerHTML = '';

  // Use a loop for the array called "country"
  country.forEach((e) => {
    // Setting variables which could be redeclared within a block
    let option = document.createElement('option');
    let text = document.createTextNode(e);
    // Appen the element with text
    option.appendChild(text);
    ville.appendChild(option);
  })
}
<select id="pays">
  <option value="Canada">Canada</option>       
  <option value="France">France</option>       
</select>

<select id="ville">


推荐阅读