简体   繁体   English

更改时不触发JavaScript选择

[英]Javascript select on change doesn't fire first try

I have the HTML code: 我有HTML代码:

<select id = "dropdownList" onchange = "dropdownChange()">
        <option> Choose a vendor </option>
    </select>

With the function: 具有的功能:

function dropdownChange(){

document.querySelector("#dropdownList").addEventListener("change",function(e){

changeVendor(this.value);
})
}

The dropdown list is already populated from an array in another function.When first selecting an item from the dropdown, it doesnt fire. 下拉列表已经从另一个函数的数组中填充了,当第一次从下拉列表中选择一个项目时,它不会触发。 However, any changes following the first do fire. 但是,先执行后的任何更改都会触发。

How can I edit my code so that when I first select an item from the dropdown it will fire right away? 如何编辑代码,这样当我第一次从下拉列表中选择一个项目时,它将立即启动?

This is how your current code works: 当前代码的工作方式如下:

  1. The first time the change event happens, dropdownChange() runs, because it's called in the element's onchange attribute. 第一次发生更改事件时, dropdownChange()运行,因为它是在元素的onchange属性中调用的。

  2. dropdownChange() now registers an event listener and returns, doing nothing else. dropdownChange()现在注册一个事件侦听器并返回,什么也不做。

  3. On the next change, the event listener registered by dropdownChange() runs and calls changeVendor(this.value) . 在下一个更改上,运行dropdownChange()注册的事件侦听器,并调用changeVendor(this.value)


You probably want: 您可能想要:

function dropdownChange() {
    changeVendor(this.value);
}

You can also call changeVendor(this.value) directly in onchange , if you'd like to avoid creating the dropdownChange() function just to call changeVendor() in it: 如果您想避免创建dropdownChange()函数只是为了在其中调用changeVendor() ,也可以在onchange直接调用changeVendor(this.value)

<select onchange="changeVendor(this.value)">
    <option>Choose a vendor</option>
</select>

You can use it like bellow, pass the value at the time of selection. 您可以像下面这样使用它,在选择时传递值。

<select id = "dropdownList" onchange = "dropdownChange(this.value)">
    <option> Choose a vendor </option>
    <option value="test"> test </option>
    <option value="test1"> test1 </option>
</select>

And javascript should be something like bellow. 而且javascript应该像下面这样。

 function dropdownChange(value) {
        alert(value);

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM