如何在jquery中运行一个函数 [英] How to run a function in jquery

查看:99
本文介绍了如何在jquery中运行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名编程新手,我无法弄清楚如何在JQuery中存储函数并在多个位置运行。



我有:

  $(function(){
$(div.class)。click(function(){
// Doo something

});

$(div.secondclass ).click(function(){
// Doo something
});

});

现在2// Doo somethings是一样的,我不想写



如果我放:

  $(函数(){

函数doosomething()
{
// Doo something
}

$(div.class) .click(dobodything);

$(div.secondclass)。click(dobodything);

});

这会在页面加载时运行该功能,而不是仅在点击时运行。



我如何正确地做到这一点?

谢谢!

解决方案

以下应该很好。

  $(function(){

//方式1
函数doosomething()
{
// Doo something
}

//方式2,等同于方式1
var dobodything = function(){
// Doo something
}

$(div.class)。click(dobodything);

$(div.secondclass)。click(dobodything);

});

基本上,你正在声明你的函数和你正在使用它的范围相同(JavaScript使用闭包来确定范围)。



现在,由于JavaScript中的函数与任何其他对象的行为类似,因此您可以简单地使用 .click(dobodything)将 doosomething 作为函数调用, ;



使用 doosomething() dobodything 没有()引用函数但不调用它)或调用另一个函数情况下,点击处理程序)。


I'm a programming newbie, and I can't figure out how to store a function in JQuery and run in it multiple places.

I have:

$(function () {
  $("div.class").click(function(){
    //Doo something

  });

  $("div.secondclass").click(function(){
    //Doo something
  });

});

Now the 2 "//Doo somethings" are the same, and I don't want to write the same code again.

If I put:

$(function () {

  function doosomething ()
  {
    //Doo something
  }

  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

That would run the function on page load, rather than only when it clicks.

How do I do this correctly?

Thanks!

解决方案

The following should work nicely.

$(function() {

  // Way 1
  function doosomething()
  {
    //Doo something
  }

  // Way 2, equivalent to Way 1
  var doosomething = function() {
    // Doo something
  }

  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

Basically, you are declaring your function in the same scope as your are using it (JavaScript uses Closures to determine scope).

Now, since functions in JavaScript behave like any other object, you can simply assign doosomething as the function to call on click by using .click(doosomething);

Your function will not execute until you call it using doosomething() (doosomething without the () refers to the function but doesn't call it) or another function calls in (in this case, the click handler).

这篇关于如何在jquery中运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆