简体   繁体   English

jQuery对不同元素的不同事件触发相同的功能

[英]jQuery different events on different elements to trigger the same function

What if different elements have to trigger the same function but on different events ? 如果不同的元素必须触发相同的功能但是在不同的事件上怎么办?

$('#btnNext').on('click', function() { /*Same thing*/ });

$('#txtField').on('change blur', function() { /*Same thing*/ });

Is there any way to integrate these two lines, so I can write the same lines of code just once ? 有没有办法整合这两行,所以我只能编写一行代码?

You included a clue in your question: "trigger the same function" - so simply bind the same function: 你在问题中包含了一个线索: “触发相同的功能” - 所以只需绑定相同的功能:

function commonHandler(e) { /* your code */ }

$('#btnNext').on('click', commonHandler);

$('#txtField').on('change blur', commonHandler);
$('#btnNext').on('click', myMethod );

$('#txtField').on('change blur',  myMethod );

function myMethod()
{
/*Your Code goes here*/
}

Here is a jsFiddle For You 这是一个适合你的jsFiddle

Fiddle Here 在这里小提琴

 function Commonalert(){alert("Common Alert Message");}

$('#Btn').on('click', Commonalert);

$('#text').on('change blur', Commonalert);

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

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