0

我希望我的按钮能够调用绑定到它们的功能。有人可以解释一下这里出了什么问题吗?我已经将功能绑定到<button>我用 Javascript 注入的一些元素,但看起来user.method第 41 行正在返回undefined

http://codepen.io/ueeeieei/pen/KNQbXO?editors=0011

var $container = $('.container');

class User {
  constructor(name, age, type) {
    this.name = name;
    this.age = age;
    this.type = type;
  }

  sing() {
    alert("singing");
    console.log("singing");
  }

  sleep() {
    alert("sleeping");
    console.log("sleeping");
  }

  collectMethods() {
    var methodNames = {
      sing: "Sing",
      sleep: "Sleep"
    };

    return methodNames;
  }
}

function createButton(user) {
  var methodNames = user.collectMethods();

  for (var method in methodNames) {
    var $btn = $('<button>' + methodNames[method] + '</button>');
    $btn.bind("click", user.method);
    $container.append($btn);
  };
}

var udi = new User("Udi", 97.2, "In-Process");
var serj = new User("Serge", "30ish", "musico-programmer")

createButton(udi);
body {
  background-color: rgba(0, 0, 0, .8);
  color: white;
}
.container {
  border: 1px solid white;
  padding: 15px;
  margin: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <!-- content here -->
</div>

4

1 回答 1

1

您的问题是因为在您的事件处理程序中,method是一个变量。要通过将对象名称存储在变量中来访问对象的属性,您必须使用括号表示法。例如,user[method]而不是user.method.

另请注意,bind()很久以前已弃用。你应该on()改用。您还应该仔细检查您正在使用的 jQuery 版本,并根据需要进行更新。我建议至少升级到 1.12。

这是您的代码的工作版本:

var $container = $('.container');

class User {
  constructor(name, age, type) {
    this.name = name;
    this.age = age;
    this.type = type;
  }

  sing() {
    alert("singing");
    console.log("singing");
  }

  sleep() {
    alert("sleeping");
    console.log("sleeping");
  }

  collectMethods() {
    var methodNames = {
      sing: "Sing",
      sleep: "Sleep"
    };

    return methodNames;
  }
}

function createButton(user) {
  var methodNames = user.collectMethods();

  for (var method in methodNames) {
    var $btn = $('<button>' + methodNames[method] + '</button>');
    $btn.on("click", user[method]); // this is the line which was fixed
    $container.append($btn);
  };
}

var udi = new User("Udi", 97.2, "In-Process");
var serj = new User("Serge", "30ish", "musico-programmer")

createButton(udi);
body {
  background-color: rgba(0, 0, 0, .8);
  color: white;
}
.container {
  border: 1px solid white;
  padding: 15px;
  margin: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <!-- content here -->
</div>

于 2016-12-04T16:52:46.490 回答