jQuery和JavaScript Namepsace [英] Jquery and javascript namepsace

查看:76
本文介绍了jQuery和JavaScript Namepsace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试对我的js/jquery代码进行命名空间时,我遇到了以下问题.

In trying to namespace my js/jquery code, I have come up against the following problem.

基本上,我以前在每个html/php文件中编写所有JS代码,我想将其抽象为带有名称空间的单个js文件.

Basically, I used to write all my JS code in each html/php file, and I want to abstract that away to a single js file with namespaces.

因此,在我的html文件中,我有:

So, in my html file I have:

<script type="text/javascript"> 
    $(document).ready(productActions.init());
</script>

在我的js文件中,我有:

And in my js file I have:

var productActions = {
    init: function() {

        alert('initialsed');

        $('#field_id').change(function() {
            alert('ok!');
        });     
    }

productActions初始化函数肯定正在运行,因为我得到了第一个警报(已初始化).但是,似乎没有一个jquery绑定函数可以执行任何操作.逐步执行init函数表明上述更改功能正在注册,但实际上更改字段中的值绝对没有任何作用.

The productActions init function is definitely running, because I get the first alert (initialised). However, it seems that none of the jquery binding functions do anything at all. Stepping through the init function shows that the above change function is being registered, but actually changing the value in the field does absolutely nothing.

我在这里错过了明显的东西吗?

Am I missing something obvious here?

推荐答案

$(document).ready(productActions.init());

此代码立即调用init() ,并将其返回值传递给ready(...). (就像其他任何函数调用一样)

This code calls init() immediately and passes its return value to ready(...). (just like any other function call)

相反,您可以写

$(document).ready(productActions.init);

传递函数本身.但是,这将使用错误的this进行调用;如果您需要this,请写

To pass the function itself. Howeverm this will call it with the wrong this; if you need this, write

$(document).ready(function() { productActions.init() });

这篇关于jQuery和JavaScript Namepsace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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