简体   繁体   English

jQuery:重构为函数

[英]jQuery: Refactoring into functions

I'm messing about with JavaScript/jQuery, and just trying to determine how to refactor two very similar: 我正在搞乱JavaScript / jQuery,并试图确定如何重构两个非常相似的:

 $('#a-div-element').click(function() {
    /* common stuff in here */
})

into one function with two arguments. 一个带有两个参数的函数。 I'd expected it to be somewhat similar to other languages I've used, that is: 我希望它与我使用过的其他语言有些相似,即:

function my_refactored_stuff(field, target_div) {
  $(field).click(function{ 
    /* common stuff in here */
  });
}

But that doesn't seem to trigger when clicked 但点击时似乎没有触发

In short, if someone could do up a quick example of how to write up a function that handles common functionality across .click methods, I'd be really appreciative 简而言之,如果有人可以快速举例说明如何编写一个处理.click方法中常见功能的函数,我会非常感激

Many thanks, PlankTon 非常感谢,PlankTon

Just define and re-use an event handler function. 只需定义并重用事件处理函数即可。

var handler = function(event) { /* common stuff here */ }
$("#a-div-element").on("click", handler)
$("#b-div-element").on("click", handler)
var callback = function() {};

$('#a-div-element').click( callback );

Or if you wish to pass arguments: 或者如果你想传递参数:

$('#a-div-element').click(function() {
    callback( /* args */ );
});

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

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