最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery different events on different elements to trigger the same function - Stack Overflow

programmeradmin0浏览0评论

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 ?

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 ?

Share Improve this question asked Jun 4, 2013 at 11:38 hsukhsuk 6,87013 gold badges52 silver badges81 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

You included a clue in your question: "trigger the same function" - so simply bind the same function:

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

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

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

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

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

Here is a jsFiddle For You

Fiddle Here

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

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

$('#text').on('change blur', Commonalert);
发布评论

评论列表(0)

  1. 暂无评论