【问题标题】:Why does this jQuery OOP property became undefined?为什么这个 jQuery OOP 属性变得未定义?
【发布时间】:2015-11-08 17:21:57
【问题描述】:

为什么点击事件后这段代码的属性没有显示?

属性this.ContainerId 在进入this.ShoutCount 方法时变得未定义。

谢谢。

var table = function (containerId) {
  this.ContainerId = containerId;
  
  this.ShoutCount = function (totalC) {
        var label = $("#" + this.ContainerId + " .result").text();
        alert(totalC + " " + label);
  }
  this.ClickCount = function (sc) {
    $("#" + this.ContainerId + " .showTotalCount").click(function () {
      sc($(this).text());
    });
  }
  this.ClickCount(this.ShoutCount);
}

var t = new table("user-tab-pagination");
<div id="user-tab-pagination">
  <div class="search-count"><span class="showTotalCount">100</span> <span class="result">Result(s)</span></div>
</div>

【问题讨论】:

  • 这属于特定的上下文,你在内部函数中使用它,所以它在那里被覆盖

标签: javascript jquery oop properties undefined


【解决方案1】:

因为一旦你进入ShoutCount 方法,this 的作用域就是那个方法,而不是外部方法。您需要使用bind 来附加您想要的范围,例如

this.ShoutCount = function (totalC) {
  var label = $("#" + this.ContainerId + " .result").text();
  alert(totalC + " " + label);
}.bind(this);

【讨论】:

    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 2022-01-14
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多