Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery在不同元素上的不同事件触发相同的函数_Javascript_Jquery - Fatal编程技术网

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);