Javascript jQuery在不同元素上的不同事件触发相同的函数
如果不同的元素必须在不同的事件上触发相同的函数,该怎么办Javascript jQuery在不同元素上的不同事件触发相同的函数,javascript,jquery,Javascript,Jquery,如果不同的元素必须在不同的事件上触发相同的函数,该怎么办 $('#btnNext').on('click', function() { /*Same thing*/ }); $('#txtField').on('change blur', function() { /*Same thing*/ }); 有没有办法集成这两行代码,这样我就可以只编写一次相同的代码行?您的问题中包含了一条线索:“触发相同的函数”-因此只需绑定相同的函数: function commonHandler(e) { /
$('#btnNext').on('click', function() { /*Same thing*/ });
$('#txtField').on('change blur', function() { /*Same thing*/ });
有没有办法集成这两行代码,这样我就可以只编写一次相同的代码行?您的问题中包含了一条线索:“触发相同的函数”-因此只需绑定相同的函数:
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*/
}
function Commonalert(){alert("Common Alert Message");}
$('#Btn').on('click', Commonalert);
$('#text').on('change blur', Commonalert);