我有以下嵌套的对象数组:
[entity{ name : "entity1",accounts [{name ="account1"}, {name ="account2"}]},
entity{ name : "entity2",accounts [{name ="account3"}, {name ="account4"}]}]]
在我的模板中,我有一个
entity
和 accounts
选择器,如下所示
label(for="entity_selector" class="form-label") Customer
select#entity_selector(class="form-select mb-4 w-25" name = "customer_id")
each entity in entities
option(value=entity._id) #{entity.name}
label(for="account_selector" class="form-label") Account
select#account_selector(class="form-select mb-4 w-25" name = "account")
当用户更改实体选择时,如何填充和更改 #account_selector 选项?我尝试了以下脚本,但它没有触发任何事件
script.
var $entities = document.getElementById('entity_selector');
$entities.addEventListener('change', function(event) {
alert('some message')
});
任何帮助将不胜感激
我使用 jQuery 解决了这个问题,希望它能帮助别人,
首先在
head tag
下添加jQuery脚本
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
现在在
body
中添加以下脚本
script.
$(document).ready(function(){
var entities = !{JSON.stringify(entities)}; // get access to pug variables fron node
//- $("#comment")[0].value = "TEST"
entities[0].accounts.forEach((account) => {
$("#account_selector").append($('<option>', {
value: account._id,
text : account.name
}));
})
})
$("#entity_selector").on('change', function() {
$("#account_selector").empty() // empty the selector
var entities = !{JSON.stringify(entities)};
var selectedIndex = this.selectedIndex
entities[selectedIndex].accounts.forEach((account) => {
$("#account_selector").append($('<option>', {
value: account._id,
text : account.name
}));
})
})
请勿使用
!{JSON.stringify(entities)};
否则您将无法访问 jQuery 脚本内的 pug 变量