首页 > 解决方案 > 如何获取 pug 文件中下拉列表的值?

问题描述

我有一个 pug 文件,它从对象(客户)列表中动态填充下拉列表,但我似乎无法获得当前从中选择的值。这是代码:

select(name="customerDropdown", id="customerDropdown" class="btn btn-success dropdown-toggle")
    each customer in customers 
      option=customer

  script.
    var el = document.getElementById('customerDropdown');
    var strCustomer = el.options[el.selectedIndex].text;

strCustomer 在此之后似乎没有任何价值。任何帮助表示赞赏!

标签: javascripthtmlpug

解决方案


请尝试以下代码,看看它是如何在您这边工作的:

- var customers = ['John','Maria','Nicolas']
select(name="customerDropdown", id="customerDropdown" class="btn btn-success dropdown-toggle")
    each customer in customers 
      option=customer
  
script.
  var $customerDropdown = document.getElementById('customerDropdown');
  
  var getSelectedCustomer = function() {
    return $customerDropdown.options[$customerDropdown.selectedIndex].text
  }
  
  $customerDropdown.addEventListener('change', function(event) {
    alert('new value: ' + getSelectedCustomer())
  });
  
  alert(getSelectedCustomer())

它应该在应用程序启动时提醒选择框 ( John) 中的第一个值,然后在您更改选择选项时提醒 - 它应该提醒选定的值。例如,如果您选择Nicolas它应该提醒 ( new value: Nicolas)

希望这会给您有关如何处理选择元素的想法。


推荐阅读