简体   繁体   English

基本jQuery:如何调用用户定义的函数

[英]Basic jQuery: How to call a user defined function

I have the following jquery function: 我有以下jQuery函数:

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

// lots of code here

});

I have another jquery event; 我还有另一个jquery事件; $("#my-second-div").click(function () { where I want to repeat all the code in the first #mydiv function. $("#my-second-div").click(function () {我要在第一个#mydiv函数中重复所有代码。

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 : 基本解决方案1:

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

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

Basic solution 2 : 基本解决方案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. 因此,当您单击#my-second-div ,它将触发对mydiv的单击并在其中运行函数。

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. 或者,您也可以堆叠Click事件。 Using the code from above only #2 would change: 仅使用上面的代码#2会发生变化:

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

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

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