javascript - 当需要使用 'this' 访问对象的函数时,$.each 中的 'this'

标签 javascript jquery

<分区>

我有一个带有名为“getHtml(elem)”的函数的对象,我想在 $.each 遍历数组时访问它。我知道“this”指的是 $.each 迭代中的元素,那么如何访问对象的函数呢?

例如:

 MyObject.prototype.doSomething = function() {
  var results = this.getElements(); //returns this object's array of objects
  var html;
  var elems = [];
  var elem;
  $.each(results, function(index, value) {
    elem = $(this); //refers to the object returned in the $.each function
    html = this.getHtml(elem); //doesn't work, this doesn't refer to this object
    elems.push(html);
  });
},

我得到的错误是:Uncaught TypeError: this.getHtml is not a function

我试图阅读 bind(),但我不明白如何使用它。如何在 $.each 中调用对象的函数?

最佳答案

由于您需要 $.each 中的上下文,因此您必须在 each 之外缓存 this 并在内部使用它。

//Other code
.
.
var _this = this;
$.each(results, function(index, value) {
    elem = $(this); 
    html = _this.getHtml(elem);
    .
    .
    //other code

关于javascript - 当需要使用 'this' 访问对象的函数时,$.each 中的 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36869484/

相关文章:

javascript - 如何将序列化数据传递到隐藏的 html 字段

javascript - 如何在javascript函数的变量中运行jsp页面

javascript - 如果标题为“无”,则隐藏/删除最后一列

javascript - Microsoft Graph API,创建附件不起作用?

javascript - 如何动态设置 AJAX 加载栏的动画直至其达到 100%?

javascript - 有没有javascript物理引擎可以模拟重力中的多边形?

javascript - MMENU根本不起作用

javascript - 任何人都知道这个网站 www.nikebetterworld.com 是如何完成的?

javascript - Bootstrap Modal 在 Firefox 中不起作用

jquery - 如何确保只调用onkeyup事件一次