简体   繁体   English

正式支持在HTML select中添加两个onChange事件处理程序吗?

[英]Is adding two onChange event handlers to an HTML select officially supported?

I was puzzling over the best way to have a second action happen when a drop-down box is changed. 当下拉框更改时,我一直在想最好的方法来执行第二个操作。 I didn't expect the following to work, I expected the dynamically added change() to replace the static one, but it did work (tested in Firefox, Chrome and Opera 12 so far). 我没想到以下方法会起作用,我希望动态添加的change()可以替代静态变量,但它确实可以工作(到目前为止已在Firefox,Chrome和Opera 12中进行了测试)。

Is this officially part of any of the HTML standards, or did I just get lucky and it might break in a future release or an older browser? 这是否正式成为任何HTML标准的一部分,还是我很幸运,它可能会在将来的版本或较旧的浏览器中失效?

<select id="testing" onChange="alert('first');">
<option></option>
<option value="1">One</option>
<option value="2">Two</option>
</select>

<script>
$('#testing').change(function(){
    alert("second");
    });
</script>

(For context, I have a Handlebars helper function making the <select> HTML, with its own onChange , which is used to hide/show an "other:" text box; now I want to perform some special actions when certain values are selected, and ideally I want to continue to use the handlebars helper, as-is.) (对于上下文,我有一个制作<select> HTML的Handlebars帮助器函数,它具有自己的onChange ,用于隐藏/显示“ other:”文本框;现在,我想在选择某些值时执行一些特殊操作,理想情况下,我想按原样继续使用车把帮助器。)

Short answer 简短答案

Yes, it is officially supported ; 是的,它得到官方支持 this is fine and won't break until the standards change. 这很好,直到标准更改才会打破。

Long(er) answer 更长的答案

The "static" on[event] ( onchange , in this case) handlers are called separately from the "dynamic" handlers added using addEventListener or similar (jQuery normalizes this for you). “静态” on[event] (在本例中为onchange )处理程序与使用addEventListener或类似方法添加的“动态”处理程序分开调用(jQuery为您将其标准化)。

In fact, many Google Web frontends use the on[event] -style handlers in their JavaScript. 实际上,许多Google Web前端在其JavaScript中使用on[event]样式的处理程序。

Further reading: 进一步阅读:

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers

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

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