Function activates whenever images load

2019-08-12 01:05发布

问题:

This is related to my previous question where the HTML is located: Grouping siblings into a div

I found it hard to explain what I was attempting to accomplish so I drew up a quick wireframe representation:

I found a different solution from grouping the content and getting the visual that is desired. The image is being held in an anchor tag so I used jQuery to find the tallest img on the page and apply that height to the containing a tag. So instead of vertical-align bottom with a fixed height set to the content I have vertical-aligned the content to the top with a Maximum Height set to the Anchor Tag and vertical-aligned the image in that tag to the bottom.

var maxHeight = 0;

$('.Product img').each(function() {
    maxHeight = Math.max(maxHeight, $(this).height()); })

$('.ProductThumbnail').css({"height":maxHeight});

The code works perfectly. However, some of the categories have several pages and when you select the "Next Page" link the eCommerce solution uses jQuery to load in the page dynamically and the code breaks.

So, my question is "How can I have the function listed above onLoad whenever images are loaded onto the page?"

[note 1:] I have already attempted to use imagesloaded by desandro and it did not work as I had hoped it would.

[note 2:] I would also like the maxHeight to be matched for each row rather than the entire page, as the TD's are kept within TR's.

[note 3:] I can not alter the html at all. I am only allowed to make addendums to the head, a custom Header, and a custom footer. The content is uneditable.

回答1:

in your case you should , or have to use this function

$('img').ready(function(){
    console.log('image is loaded');


})

it will see if the element is loaded and then preform the function ...

here is an example

jsfiddel



回答2:

You could attach a delegate to each tr (which is triggered whenever a child img fires the ready event) that recalculates that row's height:

$("table#tableId tr").on("ready", "img", function(){
       var maxHeight = 0;

       $(this).find('.Product img').each(function() {
           maxHeight = Math.max(maxHeight, $(this).height()); })

       $(this).find('.ProductThumbnail').css({"height":maxHeight});
    })
});

ETA: This code uses the live() method to delegate the event. With this method you can bind events to elements that do not exist yet. Note that live() is deprecated, and on() should be used, but to delegate with on() you need a parent element that is not replaced.

$("table#tableId img").live("ready",  function(){
       var maxHeight = 0;
       var $row = $(this).parents("tr");
       $row.find('img').each(function() {
           maxHeight = Math.max(maxHeight, $(this).height()); })

       $row.find('.ProductThumbnail').css({"height":maxHeight});
    })
});


标签: jquery onload