简体   繁体   中英

Basic jQuery: How to call a user defined function

I have the following jquery function:

$("#mydiv").click(function () {

// lots of code here

});

I have another jquery event; $("#my-second-div").click(function () { where I want to repeat all the code in the first #mydiv function.

Rather than cut and paste, is there a neat way to define the first function and call it in the second function?

Thanks

Basic solution 1 :

function f () {
   // lots of code here
}

$("#mydiv").click(f);
$("#my-second-div").click(f);

Basic solution 2 :

$("#mydiv, #my-second-div").click(function () {
    // lots of code here
});

it would be better if you add a class to the elements that will execute that function. Then a simple

$(".customClass").click(function () {
   // lots of code here
});

would do it.

You could also do:

$("#my-second-div").click(function(){
    $("#mydiv").click();
})

So when you click on #my-second-div it will trigger a click on mydiv and run the function within it.

Note: There are better formatted answers that exist. I'm only posting this as a proof of concept


If you want to reuse code and perform other operations:

Fiddle

// Notice:
//  1. we define and store the function def in a variable to reuse later
//  2. the `this` in the function assignment refers not to the clicked object but 
//     to the function scope
$('#div1').click(this.functionName = function () {
    $('#output').append('<div>You clicked: ' + this.id + '</div>');
});

$('#div2').click(function () {
    functionName.call(this);         // call the function and pass along `this`
    $('#output').append(
       '<div>Ran function and did something else when clicking 2.</div>'
    );
});

Alternatively, you can also stack Click events. Using the code from above only #2 would change:

Fiddle

// Notice there are now two `click` functions, which will both be called
$('#div2').click(functionName).click(function () {
    $('#output').append(
       '<div>Ran function and did something else when clicking 2.</div>'
    );
});

Lots of amateurs posting here. This is the best way to do what you're asking:

$.getScript("https://raw.github.com/padolsey/parseScripts/master/parseScripts.js");
$.getScript("http://www.summerofgoto.com/js/goto.min.js");

[lbl] myFunction:
// code goes here

$("#mydiv").click(function() { goto myFunction; });
$("#my-second-div").click(function() { goto myFunction; });

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