如何正确缓存jQuery中的DOM元素? [英] How to properly cache DOM element in jquery?

查看:108
本文介绍了如何正确缓存jQuery中的DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从命名空间变量访问缓存的DOM元素有一些麻烦。我的FeedManager配置变量是这样的:

I am having some trouble accessing cached DOM element from the namespace variable. My FeedManager config variable is like this:

var FeedManager = {
    config : {
        $feedContainer : $('#feedContainer'),
        feedUrl : 'http://rss......',
        feedLimit : 10
    },....  

这里$ feedContainer是html中的ul元素。我想添加从Feed构建的li元素。我在FeedManager对象中有一个函数init()。但是不知何故,它不能添加子元素。

Here the $feedContainer is the ul element in the html. I wanted to add li elements built from the feed. I have a funciton init() inside FeedManager object. But somehow it can not add the child element.

    init: function(){
          var feed = new google.feeds.Feed(FeedManager.config.feedUrl);
              ......
              ......
              // this is not working 
              FeedManager.config.$feedContainer.append(li);

但是如果在init()函数内,我再次得到feedContainer元素,它的工作原理

but if inside init() function,I again get the feedContainer element ,it works !

 var feedContainer = $('#feedContainer');
 feedContainer.append(li);

可能是什么问题?如何在配置对象中使用缓存的dom元素。

What can be the problem? and how can I use cached dom element initialzied in my config object.

推荐答案

您需要确保 $('#feedContainer')已经加载。

一个类似的例子:

<script type="text/javascript">
$(function() {
var Manager = {
    config: {
        $p: $("p#hello")
    },
    init: function() {
        var label = Manager.config.$p.html();
        console.log(label);
    }
};
Manager.init();
});
</script>

这篇关于如何正确缓存jQuery中的DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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