【问题标题】:Add function to Object with an element selector [closed]使用元素选择器向对象添加函数 [关闭]
【发布时间】:2015-03-20 15:36:51
【问题描述】:

我有一个对象

function Object(name, button) {
    this.name = name;
    this.button = button;
    var alert = function () {
        alert("x");
    };
}

var ExampleOne = new Object('Example One', $('.exampleButton'));

如何使对象内的函数在 Object[button] 事件时触发...

使用 -

ExampleOne.button.click(function () {
    ExampleOne.alert();
});

没用。

【问题讨论】:

  • 在这里可以正常工作:jsfiddle.net/dkqd4q5o - 确保在分配该选择器时,DOM 已被解析。
  • var alert 是一个局部变量...如果您想从新对象访问它,请使用this - jsfiddle.net/qow3qu0m/2 声明
  • tymeJV - 如果我只使用函数 alert(){...});
  • -_- 对不起,伙计们。 JS对象101!我将编辑问题以使其更具可读性,以防更多新手出现相同的问题。感谢您的帮助
  • 想回答,tymeJV?

标签: javascript jquery object events


【解决方案1】:

var alert = function 是一个本地函数,不能在该对象之外访问。如果您希望新实例可以访问它,请使用this 声明它:

function Object(name, button) {
    this.name = name;
    this.button = button;
    this.alert = function () {
        alert("x");
    };
}

小提琴:http://jsfiddle.net/qow3qu0m/2/

【讨论】:

    【解决方案2】:

    它对我有用。再次检查您的代码。也许你忘了包含 jQuery?

    ExampleOne.button.click(function(e) {
      alert('success!');
    });
    

    http://codepen.io/anon/pen/yyGpLz

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多