How to properly cache DOM element in jquery?

前端 未结 2 1429
陌清茗
陌清茗 2021-01-15 13:19

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

var FeedManager = {
    confi         


        
相关标签:
2条回答
  • 2021-01-15 13:30

    You'd need to make sure the $('#feedContainer') has already been loaded.

    An analogous example:

    <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>
    
    0 讨论(0)
  • 2021-01-15 13:48

    Is your #feedContainer element present in your HTML or is it fetched later? If it is fetched later than you can't cache the element, you'd have to use just a selector string like feedContainer: '#feedContainer'`

    in your FeedManager object and then use something like

    $(FeedManager.config.feedContainer).append(li);
    

    If it is present in HTML then make sure that you define your FeedManager object after the DOM is ready, ie. inside of a

    $(document).ready(function () {
        // ...
    });
    

    or $(function () { ... });

    0 讨论(0)
提交回复
热议问题