[英]How to make an input have more than one event?
I have a button and a select in my form. 我的表单中有一个按钮和一个选择。 The button has onclick
event while the select has onchange
event. 该按钮具有onclick
事件,而select具有onchange
事件。 How to make the select has both onclick
and onchange
event? 如何使选择同时具有onclick
和onchange
事件?
This is the script: 这是脚本:
$('#i_btn').on('click', function(){
alert('Event 1');
});
$('#i_sel').on('change', function(){
alert('Event 2');
});
When the select is changed, it should do alert('Event 1'); alert('Event 2');
当选择更改时,它应该执行alert('Event 1'); alert('Event 2');
alert('Event 1'); alert('Event 2');
. 。 I do not want to rewrite the onclick
code in onchange
我不想在onchange
重写onclick
代码
You can trigger the click event of #i_btn in the change event of #i_sel 您可以在#i_sel的更改事件中触发#i_btn的点击事件
$('#i_btn').on('click', function(){
alert('Event 1');
});
$('#i_sel').on('change', function(){
alert('Event 2');
$("#i_btn").trigger("click");
});
Write your events as separate functions : 将事件编写为单独的函数:
$('#i_btn').on('click', event1);
$('#i_sel')
.on('change', event1)
.on('change', event2);
function event1(){
alert('Event 1');
}
function event2(){
alert('Event 2');
}
You can use trigger inside the on change of the select make sure you have defined buttons on click before on change 您可以在select的on更改内使用触发器,以确保在change之前定义了单击按钮
$('#btn1').on('click', function(){ alert('Clicked'); }); $('#select1').on('change', function(){ alert('Changed'); $("#btn1").trigger("click"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <select id="select1"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <button id="btn1">click</button>
You could also simply add the event handler to the element... 您也可以简单地将事件处理程序添加到元素中...
$('#i_btn, #i_sel').on('click', function(){
alert('Event 1');
});
$('#i_sel').on('change', function(){
alert('Event 2');
});
Unless you really need the click to trigger on the button... 除非您确实需要单击以触发按钮...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.