如何缓存jQuery选择?

Dav*_*Fox 2 javascript jquery caching jquery-selectors

我需要缓存大约100种不同的动画选择.以下是示例代码.第二个示例中是否存在语法问题?如果这不是缓存选择方式,它肯定是互联网上最受欢迎的.那么,我错过了什么?

注意:p$.path.bezier(p)下面是传递给jQuery.path.bezier正确声明的对象(真棒动画库,顺便说一句)

有效

    $(document).ready(function() {
        animate1();
        animate2();
    })
    function animate1() {
        $('#image1').animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate1()", 3000);
    }
    function animate2() {
        $('#image2').animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate2()", 3000);
    }
Run Code Online (Sandbox Code Playgroud)

不起作用

    var $one = $('#image1'); //problem with syntax here??
    var $two = $('#image2');
    $(document).ready(function() {
        animate1();
        animate2();
    })
    function animate1() {
        $one.animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate1()", 3000);
    }
    function animate2() {
        $two.animate({ path: new $.path.bezier(p) }, 3000);
        setTimeout("animate2()", 3000);
    }
Run Code Online (Sandbox Code Playgroud)

Sea*_*ira 5

如果在调用它们时未加载图像,jQuery将返回一个空对象.在您的document.ready函数中移动您的作业:

$(document).ready(function() {
    var $one = $('#image1');
    var $two = $('#image2');
    animate1();
    animate2();
});
// ... etc.
Run Code Online (Sandbox Code Playgroud)

如果需要将它们缓存以供以后在初始化脚本之外使用,请将它们添加到存储对象:

var my_storage_object = {};
$(document).ready(function() {
    var $one, $two;
    my_storage_object.$one = $one = $('#image1');
    my_storage_object.$two = $two = $('#image2');
    animate1();
    animate2();
});
// ... etc.
Run Code Online (Sandbox Code Playgroud)

然后,document.ready你可以打电话给:

my_storage_object.$one //still has a reference to the jQuery object.
Run Code Online (Sandbox Code Playgroud)