簡體   English   中英

對象文字內部的jQuery

[英]JQuery Inside An Object LIteral

我在JS中有以下代碼片段:

var Mylib = Mylib || function(){

    var $cart         = $('#topbar_cart_value');
    var _cartObj = {
        total: 0,
        items: 0
    };    
    /**
     * 
     * @type String|el
     */
    function render() {
        //Render the total in cart
        var str = "€" + str.replace(".",",");
        $cart.html(str); <--
        // THIS IS GETTING SELECTED OK!
        console.log(document.getElementById('topbar_cart_value'));
       // THIS IS GETTING SELECTED OK!
        console.log($('#topbar_cart_value'));
       // BUT THIS IS GETTING SELECTED WITH LENGHT 0! ....
        console.log($cart);
       // ...AND THEN...
        $cart.html(str); //<--DOES NOT SET THE value
    }
return {
        init : function() {
              cacheDom();
            },
            getCartObj : getCartObj,
            setCartObj : setCartObj,  
            addToCartObj: addToCartObj,
    };
}();
Mylib.init(); 
/** ..........AFTER MANY BLOCKS OF HTML AND JS ...............**/

 $(document).ready(function() { unimanlib.init( 
            {'cart_sel':'span#topbar_cart_value'
            }); });

該問題在render函數中進行了解釋。最后一個日志的控制台是:

[prevObject: m.fn.init[1], context: document, selector: "#topbar_cart_value"]
context: document
length: 0
prevObject:m.fn.init[1]
selector:"#topbar_cart_value"
__proto__: Object[0]

這段代碼

var $cart = $('#topbar_cart_value');

創建Mylib對象后,就會調用,而我認為您是在呈現實際的html之前創建它的。

您應該使用Mylib.init(); $(document).ready函數中

檢查元素ID #topbar_cart_value是否對該元素唯一。 還要檢查標記是否為#topbar_cart_value的直接子代,因為如果其中任何一項為假,則標記將不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM