jQuery不同的事件在不同的元素上触发相同的function
如果不同的元素必须触发相同的function但是在不同的事件上怎么办?
$('#btnNext').on('click', function() { /*Same thing*/ }); $('#txtField').on('change blur', function() { /*Same thing*/ });
有没有办法整合这两行,所以我只能编写一行代码?
你在问题中包含了一个线索: “触发相同的function” – 所以只需绑定相同的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*/ }
这是一个适合你的jsFiddle
在这里小提琴
function Commonalert(){alert("Common Alert Message");} $('#Btn').on('click', Commonalert); $('#text').on('change blur', Commonalert);