0

I currently call a function when lazyload has rendered an image. This works fine. The problem I have is that i need to access $(this) within the function. Is there a way of parsing this data to the function?

Fiddle http://jsfiddle.net/DTcHh/19852/

$("img").lazyload({
  load: equalizeHeights
});

function equalizeHeights() 
{
  //var classStr = '.'+$(this).parent('div').attr('class');
  var classStr = '.my-wrapper';
  var heights = $(classStr).map(function() {
      return $(this).height();
    }).get(),
    maxHeight = Math.max.apply(null, heights);

  $('.my-wrapper').height(maxHeight);
}
4

2 回答 2

0

您可以使用Function.prototype.bind()附加的值this

例子:

var obj= {
 someData: "Hello"
}

function printSomeData() {
  console.log(this.someData);
}

var customFunction = printSomeData.bind(obj);

customFunction(); //withing the function, "this" is obj, so it will print "Hello"

所以在你的情况下,我想你可以使用类似的东西

$("img").lazyload({
  load: equalizeHeights.bind($("img"))
});

(不确定您要使用的“this”是什么)

于 2016-04-26T10:12:26.080 回答
0

您使用的插件实际上有一个回调函数。例子:

$("img.lazy").lazyload({
    load : function(elements_left, settings) {
        console.log(this, elements_left, settings);
        $(document).trigger("something");
    }
});

在你的情况下,你会像这样使用它:

演示http://jsfiddle.net/DTcHh/19856/

$("img").lazyload({
  effect: "fadeIn",
  threshold: 300,
  failure_limit: 10,
  load: function(elements_left, settings) {
    equalizeHeights(this);
  }
});

function equalizeHeights(ele) 
{
  var classStr = '.'+$(ele).parent('div').attr('class');
  var heights = $(classStr).map(function() {
      return $(this).height();
    }).get(),
    maxHeight = Math.max.apply(null, heights);

  $('.my-wrapper').height(maxHeight);
}

我认为这是您所追求的用例。

于 2016-04-26T10:53:45.673 回答