简体   繁体   English

使用模块模式在jQuery回调中访问私有变量

[英]Accessing private variables in a jQuery callback with the module pattern

The below executes without errors, but the DOM isn't updated. 下面执行没有错误,但DOM没有更新。

var Cart = function() {
  var $cart;

  function init() {
    $cart = $("#cart");

    this.refresh();
  }

  function refresh() {
    $.ajax({
      // ...
      success: function(html) {
        $cart.html(html); // $cart seems to exist as JS object, but #cart doesn't get updated in the DOM.
        $("#cart").html(html); // This works!
      }
    });
  }

  return {
    init: init,
    refresh: refresh
  }
}();

$(function() {
  Cart.init();
});

Update 更新

I wasn't actually calling Cart.init() inside the jQuery ready event contra to what the code above says. 我实际上并没有在jQuery ready事件中调用Cart.init(),这与上面的代码相反。

Check your #cart object exists when you call Cart.init() . 调用Cart.init()时检查#cart对象是否存在。 That's the only difference I see between your two working and not working code as there is no other problem (see fiddle ). 这是我在你的两个工作代码和不工作代码之间看到的唯一区别,因为没有其他问题(参见小提琴 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM