如何在 jQuery 中创建和调用自定义函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18393448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:31:12  来源:igfitidea点击:

how to create and call a custom function in jQuery

jqueryfunction

提问by user1911703

I need to create a simple function in jQuery which will call within other few functions

我需要在 jQuery 中创建一个简单的函数,它将在其他几个函数中调用

$(document).ready(function() {
  function reload_cart() {
    alert('reload cart called');
  }
});
$(document).ready(function() {
  reload_cart(); //i need to call from here.
});
$(document).ready(function() {
  $('a.add_to_cart').live('click', function (e) {
    reload_cart(); //i need to call from here.
  });
});

The error I get in firebug: reload_cart() is not defined.

我在萤火虫中得到的错误:reload_cart() is not defined

回答by Blender

reload_cartis local to your first $(document).ready()callback. You can't call it from an outside scope.

reload_cart是您的第一个$(document).ready()回调的本地。您不能从外部范围调用它。

You should merge your functions together:

您应该将您的功能合并在一起:

$(document).ready(function() {
    function reload_cart() {
        alert('reload cart called');
    }

    reload_cart();

    $('a.add_to_cart').live('click', function(e) {
        reload_cart();
    });
});

An even better solution would be to create a cartobject, add reloadto its prototype, and initialize it outside of all of the callbacks.

一个更好的解决方案是创建一个cart对象,添加reload到它的原型,并在所有回调之外初始化它。

回答by ced-b

Yes, because you declared the function within the scope of the first $(document).ready(function(){})so it will not be available outside of that functions scope.

是的,因为您在第一个范围内声明了该函数,$(document).ready(function(){})因此它在该函数范围之外将不可用。

I am not sure why you would call $(document).ready()more than once. Try this:

我不知道为什么你会$(document).ready()不止一次打电话。尝试这个:

$(document).ready(function(){
   function reload_cart() {
       alert('reload cart called');
   }

   reload_cart(); //i need to call from here.


   $('a.add_to_cart').live('click', function(e) {
       reload_cart(); //i need to call from here.
   });
});

Alternatively you can also declare your function outside of $(document).ready()and it will be globally available.

或者,您也可以在外部声明您的函数$(document).ready(),它将在全球范围内可用。

回答by Akhil Sekharan

Put your function definition:

把你的函数定义:

function reload_cart() {
    alert('reload cart called');
}

Outside document.ready.

外部文档。准备好了。

Currently, Its scoped inside the document.ready handler only.

目前,它的范围仅限于 document.ready 处理程序。

$(document).ready(function(){
//reload_cart is only available here
    function reload_cart() {
        alert('reload cart called');
    }
});