JQuery在图像上加载事件

Hub*_*ron 2 jquery load image handler

我想在加载图像时将图像父级的大小调整为相同大小的图像.

这时候我正在使用这段代码:

$(window).load(function(){
    $('.image-principale').each(function(){
        $(this).parent().css('height', $(this).height());
    });
});
Run Code Online (Sandbox Code Playgroud)

它工作,除了它只在每个图像加载时运行.我试图直接为每个图像添加一个加载处理程序,但它们不会触发.

怎么了?

谢谢!

SLa*_*aks 5

请尝试以下方法:

...Your HTML...

<script type="text/javascript">
    $('.image-principale').load(function(){
        $(this).parent().css('height', $(this).height());
    });
</script>
Run Code Online (Sandbox Code Playgroud)

请注意,脚本必须放在HTML之后,否则它将在<img>元素存在之前运行,并且实际上不会执行任何操作.

您也可以尝试使用live,如下所示:

$('.image-principale').live('load', function(){
    $(this).parent().css('height', $(this).height());
});
Run Code Online (Sandbox Code Playgroud)

但是,我不知道它是否真的有效.