如何触发选定的选项事件



我正在尝试编写一些Javascript(不是Jquery(,当单击地址下拉字段时,它将触发一个事件来检查"发货状态"字段中的值。

<script>
var addressDropdown = document.querySelector('#address-id');
var shipstateDropdown = document.querySelector('#shipstate-id');
var SelectedShipState;
addressDropdown.addEventListener('click', (addressEvent) => {
if (shipstateDropdown.options[shipstateDropdown.selectedIndex].value === "CA") {
    SelectedShipState = "CA";
    RunRule();
        }
})
</script>

我解决了我的问题。我首先必须为地址下拉列表设置事件处理程序,当发生这种情况时,它会触发一个函数。然后,该函数从发货状态下拉列表中获取值。

我还添加了 setTimeout,因为触发地址处理程序的行为是在值到达之前抓取船状态,从而导致值延迟或 null。

// Global defined variables //
var SelectedShipState
var selectElement = document.getElementById('ship-state-id');
var addressBook = document.getElementById('address-book-id');
// Change Event: When an address from the address book is selected ...
addressBook.addEventListener('change', (addressEvent) => {
// ... run this function to get the ship state.
setTimeout(addressFunction, 1000);
    })
// When this function runs ...
function addressFunction() {
// ... get the value from the ship state select option.
SelectedShipState = this.selectElement.options[selectElement.selectedIndex].value;
RunRule();
    }
// Change Event : Get the option each time it is selected //
selectElement.addEventListener('change', (changeEvent) => {
SelectedShipState = `${changeEvent.target.value}`;
RunRule();
})
function RunRule () {
// do something ...
}

相关内容

  • 没有找到相关文章

最新更新