且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基于相同的html表单中的另一个下拉列表填充一个下拉列表

更新时间:2023-01-07 21:41:06

您可以使用对象来保存值及其关联的下拉菜单描述.为此,您首先需要在下拉菜单中添加事件侦听器,以便在您选择新水果时它将检测到更改.使用更改事件侦听器,可以检索使用this.value选择的选项的值.

You can achieve this using an object to hold the values and their associated dropdown's descriptions. In order to do this, you firstly need to add an event listener to your dropdown so that it will detect a change when you pick a new fruit. Using the change event listener, you can retrieve the value of the option which was selected using this.value.

使用所选选项中的value,您可以继续从名为prices的对象获取其关联的下拉列表的值(这将返回一个数组).一旦获得此数组,就可以遍历它,并使用.reduce()构建" HTML字符串作为price select标记的选项.构建完此字符串后,您可以使用.innerHTML将其附加到select标记内,该代码将HTML字符串转换"为DOM对象(实际元素,而不仅仅是文本):

Using the value from the option selected, you can proceed to get its associated dropdown's values from the object called prices (this will return an array). Once you've gotten this array, you can loop through it and "build" a string of HTML using .reduce() to place as the options for the price select tag. Once you've built this string, you can append it inside the select tag using .innerHTML which "converts" your HTML string to DOM objects (real elements rather than just text):

const prices = {"apple":[{value:3,desc:"Apple 1kg 3€"},{value:5,desc:"Apple 2kg 5€"},{value:7,desc:"Apple 3kg 7€"}],
             "banana":[{value:3,desc:"Banana 2kg 3.5€"},{value:5,desc:"Banana 4kg 7€"},{value:7,desc:"Banana 5kg 11€"}],
             "peach":[{value:3,desc:"Peach 1.5kg 3€"},{value:5,desc:"Peach 3kg 6€"},{value:7,desc:"Peach 4kg 7€"}]}

const price = document.querySelector('[name=price]');
document.querySelector('[name=fruit]').addEventListener('change', function(e) {
  price.innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});

<select name="fruit">
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="peach">Peach</option>
</select>
<br />
<select name="price">
  <option value="3">Apple 1kg 3€</option>
  <option value="5">Apple 2kg 5€</option>
  <option value="7">Apple 3kg 7€</option>
</select>

如果您不习惯使用.reduce(),则可以改用常规的for循环:

If you don't feel comfortable using .reduce() you can use a regular for loop instead:

...  
let options = "";
for(obj of prices[this.value]) {
  options += '<option value="' +obj.value +'">' +obj.desc +'</option>';
}
price.innerHTML = options;
...