每个()完成后的触发功能 [英] Fire function after each() has completed

查看:83
本文介绍了每个()完成后的触发功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与这个问题有一点关系 在.each()完成后调用jQuery函数

this is slightly related to this question Invoking a jQuery function after .each() has completed

但是该解决方案似乎不太适合我.

But the solution doesn't quite seem to work for me.

基本上,我有一段JavaScript可以计算某些元素的宽度:

Basically I have piece of JavaScript that calculates the width of some elements:

var totalWidth = 0;
$element.find('li').each(function () {
    totalWidth += $(this).width();
});

在此之后,我想使用宽度设置另一个元素:

After this I want to then use the width to set another element:

$element.width(totalWidth);

如果我连接调试器,它就可以工作,但是如果我只是运行它,它就不行.这使我认为宽度是在.each()完成之前设置的.

If I attach the debugger it works but if I just run it it doesn't. Which makes me think that the width is being set before the .each() completes.

我尝试使用.promise()修复此问题,但似乎没有什么不同.

I tried using .promise() to fix this issue but it doesn't appear to make a difference.

var totalWidth = 0;
$element.find('li').each(function () {
    totalWidth += $(this).width();
});

$element.promise().done(function () {
    $element.width(totalWidth);
});

这是我的HTML

<div class="carousel">
        <ul>
            <li>
                <img src="/Images/Travel2New/Adverts/advertHolder_1.png" />
            </li>
            <li>
                <img src="/Images/Travel2New/Adverts/advertHolder_2.png" />
            </li>
            <li>
                <img src="/Images/Travel2New/Adverts/advertHolder_3.png" />
            </li>
            <li>
                <img src="/Images/Travel2New/Adverts/advertHolder_4.png" />
            </li>
            <li>
                <img src="/Images/Travel2New/Adverts/advertHolder_5.png" />
            </li>
        </ul>
    </div>

有什么想法吗?

推荐答案

由于宽度计算应等到图形被加载后,您才可以尝试以下操作:

Since your width calculation should wait until the graphics is loaded then you can try the following:

$(window).load(function () {
    var totalWidth = 0;

    $element.find('li').each(function () {
        totalWidth += $(this).width();
    });

    $element.width(totalWidth);
});

load() 事件示例说明中,我们可以看到:

From load() event example description we can see:

在页面完全加载后运行功能,包括图形.

Run a function when the page is fully loaded including graphics.

$(window).load(function () {
    // run code
});

请注意,目前load()事件似乎已已弃用,因此您应该考虑您利用的jQuery版本.

Note that at the moment the load() event seems to be deprecated, so you should consider the version of jQuery you exploit.

这篇关于每个()完成后的触发功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆