Html 使用 JavaScript 更改 <select> 的选项和触发事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19329978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:23:12  来源:igfitidea点击:

Change <select>'s option and trigger events with JavaScript

javascripthtmldomhtml-selectdom-events

提问by user1798933

How can I change an HTML <select>'s option with JavaScript (without any libraries like jQuery), while triggering the same events as if a user had made the change?

如何<select>使用 JavaScript更改 HTML的选项(没有任何像 jQuery 这样的库),同时触发与用户进行更改相同的事件?

For example using following code, if I change the option with my mouse then an event triggers (i.e. onchangeis run). However, when I change the option using JavaScript then it doesn't fire any event. Is it possible to fire trigger associated event handlers like onclick, onchange, etc., when an option is selected with JavaScript?

例如,使用以下代码,如果我用鼠标更改选项,则会触发一个事件(即onchange运行)。但是,当我使用 JavaScript 更改选项时,它不会触发任何事件。当使用 JavaScript 选择一个选项时onclick,是否可以触发相关的事件处理程序,如onchange、 等?

<select id="sel" onchange='alert("changed")'>
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true;' value="Change option to 2" />

http://jsfiddle.net/xwywvd1a/

http://jsfiddle.net/xwywvd1a/

回答by Lewis

Unfortunately, you need to manually fire the changeevent. And using the Event Constructorwill be the best solution.

不幸的是,您需要手动触发change事件。使用事件构造函数将是最好的解决方案。

var select = document.querySelector('#sel'),
    input = document.querySelector('input[type="button"]');
select.addEventListener('change',function(){
    alert('changed');
});
input.addEventListener('click',function(){
    select.value = 2;
    select.dispatchEvent(new Event('change'));
});
<select id="sel" onchange='alert("changed")'>
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3' selected>Three</option>
</select>
<input type="button" value="Change option to 2" />

And, of course, the Eventconstructor is not supported in IE. So you may need to polyfill with this:

而且,当然,Event构造函数在 IE 中不受支持。所以你可能需要用这个 polyfill:

function Event( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
}

回答by Karol

Fiddle of my solution is here. But just in case it expires I will paste the code as well.

我的解决方案的小提琴是here。但以防万一它过期,我也会粘贴代码。

HTML:

HTML:

<select id="sel">
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" id="button" value="Change option to 2" />

JS:

JS:

var sel = document.getElementById('sel'),
    button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;

    // firing the event properly according to StackOverflow
    // http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually
    if ("createEvent" in document) {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent("change", false, true);
        sel.dispatchEvent(evt);
    }
    else {
        sel.fireEvent("onchange");
    }
});

sel.addEventListener('change', function (e) {
    alert('changed');
});

回答by galeonweb

It is as simple as this:

就这么简单:

var sel = document.getElementById('sel');
var button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;
    sel.onchange();
});

But this way has a problem. You can't call events just like you would, with normal functions, because there may be more than one function listening for an event, and they can get set in several different ways.

但是这种方式有问题。您不能像使用普通函数那样调用事件,因为可能有多个函数在侦听一个事件,并且可以通过几种不同的方式设置它们。

Unfortunately, the 'right way' to fire an event is not so easy because you have to do it differently in Internet Explorer (using document.createEventObject) and Firefox (using document.createEvent("HTMLEvents"))

不幸的是,触发事件的“正确方法”并不那么容易,因为您必须在 Internet Explorer(使用 document.createEventObject)和 Firefox(使用 document.createEvent("HTMLEvents"))中以不同的方式执行此操作

var sel = document.getElementById('sel');
var button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;
    fireEvent(sel,'change');

});


function fireEvent(element,event){
    if (document.createEventObject){
    // dispatch for IE
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt)
    }
    else{
    // dispatch for firefox + others
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true ); // event type,bubbling,cancelable
    return !element.dispatchEvent(evt);
    }
}

回答by Ryan Wheale

The whole creating and dispatching events works, but since you are using the onchangeattribute, your life can be a little simpler:

整个创建和调度事件都可以工作,但是由于您使用了该onchange属性,您的生活可以简单一点:

http://jsfiddle.net/xwywvd1a/3/

http://jsfiddle.net/xwywvd1a/3/

var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();

If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.

如果您使用浏览器的事件 API(addEventListener、IE 的 AttachEvent 等),那么您将需要创建和调度事件,正如其他人已经指出的那样。

回答by Vicky Gonsalves

Try this:

尝试这个:

<select id="sel">
 <option value='1'>One</option>
  <option value='2'>Two</option> 
  <option value='3'>Three</option> 
  </select> 


  <input type="button" value="Change option to 2"  onclick="changeOpt()"/>

  <script>

  function changeOpt(){
  document.getElementById("sel").options[1].selected = true;

alert("changed")
  }

  </script>

回答by mmaynar1

These questions may be relevant to what you're asking for:

这些问题可能与您的要求有关:

Here are my thoughts: You can stack up more than one call in your onclick event like this:

这是我的想法:您可以像这样在 onclick 事件中堆叠多个调用:

<select id="sel" onchange='alert("changed")'>
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true; alert("changed");' value="Change option to 2" />

You could also call a function to do this.

您也可以调用函数来执行此操作。

If you really want to call one function and have both behave the same way, I think something like this should work. It doesn't really follow the best practice of "Functions should do one thing and do it well", but it does allow you to call one function to handle both ways of changing the dropdown. Basically I pass (value) on the onchange event and (null, index of option) on the onclick event.

如果你真的想调用一个函数并且两者都以相同的方式运行,我认为这样的事情应该可行。它并没有真正遵循“函数应该做一件事并做好”的最佳实践,但它确实允许您调用一个函数来处理更改下拉列表的两种方式。基本上我在 onchange 事件上传递 (value) 并在 onclick 事件上传递 (null, index of option)。

Here is the codepen: http://codepen.io/mmaynar1/pen/ZYJaaj

这是代码笔:http://codepen.io/mmaynar1/pen/ZYJaaj

<select id="sel" onchange='doThisOnChange(this.value)'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" onclick='doThisOnChange(null,1);' value="Change option to 2"/>

<script>
doThisOnChange = function( value, optionIndex)
{
    if ( optionIndex != null )
    {
       var option = document.getElementById( "sel" ).options[optionIndex];
       option.selected = true;
       value = option.value;
    }
    alert( "Do something with the value: " + value );
}
</script>

回答by eldano

You can fire the event manually after changing the selected option on the onclick event doing: document.getElementById("sel").onchange();

您可以在更改 onclick 事件上的选定选项后手动触发事件: document.getElementById("sel").onchange();

回答by Primoshenko

html using Razor:

html 使用剃刀:

 @Html.DropDownList("test1", Model.SelectOptionList, new { id = "test1", onchange = "myFunction()" })

JS Code:

JS代码:

function myFunction() {

            var value = document.getElementById('test1').value;

            console.log("it has been changed! to " + value );
        }