javascript - 如何获取 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 在此之后似乎没有任何价值。任何帮助表示赞赏!
解决方案
请尝试以下代码,看看它是如何在您这边工作的:
- 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
)
希望这会给您有关如何处理选择元素的想法。
推荐阅读
- c++ - 是否有用于具有固定运行时确定大小的数组的标准 C++ 类?
- mqtt - Mosquitto >1.5 用户访问级别通配符
- javascript - 为什么要在字符串中拆分脚本结束标记?
- datatables - YADCF range_slider 在 beta-21 发布后未显示
- appium - 如何附加appium服务器日志
- laravel-5 - 在 AppServiceProvider.php 引导中使用引用 db 安装 laravel 5 应用程序时出错
- azure - Azure Function Blob 触发器不响应手动导入
- hive - 如何根据 Impala 查询中的调整找到值的总和
- javascript - 如何让“appendChild”创建的 div 使用已经存在的样式
- docker - docker compose tcpdump 没有显示任何内容