【问题标题】:Accesing $this outside foreach loop Jquery在foreach循环Jquery之外访问$this
【发布时间】:2017-07-06 18:04:28
【问题描述】:
jQuery('.webform-component-checkboxes').each(function(){
    var height = heightAdjustment(jQuery(this));
    console.log(height);
});

function heightAdjustment(variable){
    var temp = 0;
    var elements = {};
    var max;
    jQuery(variable).find('.form-checkboxes .form-type-checkbox label.option').each(function() {
        max = jQuery(this).parent().css('height');
        temp = temp > max ? temp : max ;
        elements = this;    
    });

    elements.parent('div').siblings().css('height',temp);
}

我正在使用此代码,但“元素”的值在循环外变为空。但它在里面工作。

帮帮我!

【问题讨论】:

  • 你刚才说的,元素只能在函数范围内使用。
  • 您不需要在 jQuery 标记中重新包装 variable,因为您已经将 jQuery 对象传递给它。另外,elements 是一个常规对象,而不是 jQuery 元素的集合,所以你的最后一行会失败。
  • elements 应该包含什么?什么不工作?
  • 元素应该包含 $this 在里面的整个对象

标签: jquery foreach this


【解决方案1】:
  1. 无需重新包装 variable,因为它已经是一个 jQuery 对象。
  2. 您的elements 是一个常规对象,而不是jQuery 元素的集合。如果您希望它存储 jQuery 元素列表,只需将其声明为变量并将其设置为选择器。
  3. 您正在执行console.log(height),但您的函数heightAdjustment() 没有返回任何内容。我添加了return temp;,以便该函数返回设置受影响元素的高度。
var elements;

jQuery('.webform-component-checkboxes').each(function(){
    var height = heightAdjustment(jQuery(this));
    console.log(height);
});

function heightAdjustment(variable){
    var temp = 0;
    var max;
    elements = variable.find('.form-checkboxes .form-type-checkbox label.option');
    elements.each(function() {
        max = jQuery(this).parent().css('height');
        temp = temp > max ? temp : max ;   
    });

    elements.parent('div').siblings().css('height',temp);
    return temp;
}

【讨论】:

  • 但现在它给出了未定义的输出,console.log(elements.css('height'));
  • 因为elements是在heightAdjustment();的范围内声明的,在外面是不可用的。你在哪里叫它?查看我的最新编辑,也许它可以解决您的问题。
  • 我无法访问元素变量的父级。
  • 你能告诉我们你想要实现什么,而不是含糊地指出你“不能做”的事情吗?如果我们知道您要做什么,那么修复您的代码会容易得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 2013-08-03
  • 2021-01-21
  • 1970-01-01
相关资源
最近更新 更多