简体   繁体   中英

how to properly call jquery functions

what is the best way of creating functions using jquery rather than just attaching functions to a button press.

at the moment I am calling regular javascript functions from jquery.

function generate_random(){}
$(click).click(function(){
     generate_random();
})

There should be no need to wrap the call in an extra layer of function... so you can write;

function generate_random(){}
$(click).click(generate_random)

Function name are really just function pointers, which is also what is generated when you create an anonymous function like in ..click(function(){...})

That's a perfectly reasonable way to call a function in jQuery, assuming the first 'click' is actually an element selector. Alternatively, you can put whatever code is inside the generate_random() function into the place where you're currently calling generated_random() (ie inside the jQuery click function)

Assuming your generate_random does not take any parameters (that would overwise conflict with parameters passed by jQuery event handler) you can rewrite that code simply as

function generate_random(){/* body */}
$(click).click(generate_random);

Alternatively if you are not calling generate_random anywhere else, then this would be more appropriate

$(click).click(function() {/* body */});

you could use .on() (jQuery 1.7.x)

$(selector).on('click', function(){
    //functionality  generate_random
});    

or

$(selector).on('click', generate_random);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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