【问题标题】:JQuery .each just gets the first two elements from array of auto generated elementsJQuery .each 只从自动生成的元素数组中获取前两个元素
【发布时间】:2017-11-05 21:20:04
【问题描述】:

我有一个 for 循环,它为我生成了一些 divspanel

@for(comment <- event.getCommentsSorted()) {

现在我想使用 jQuery 更改每个 div,但 .each 只使用 panel 类获取前两个 divs

$(window).on('load', function() {
        $(".panel").each(function (index) {
            alert(index);
            $(this).height($(this)[index].scrollHeight - 12);
        });
    });

其他三个 div 不存在。

我想可能是因为脚本在所有divs 生成之前执行,但load 脚本应该在页面加载后执行。 我也尝试使用.ready 或生成不同数量的divs,但我只得到前两个元素并不重要。

那么为什么我只得到前两个元素,有没有办法得到所有元素?

【问题讨论】:

  • 页面加载后脚本正在添加其他声音
  • 我认为您的 for 循环在页面加载后运行。尝试在 for 循环中添加一些控制台消息/警报并找到执行顺序。
  • 听起来像是事件委托的工作。您的元素究竟是如何添加的?
  • 我将尝试在循环中添加警报。 div 直接添加到循环中。首先,我检查数据库中是否要生成 cmets(divs)。如果是,则循环遍历所有 cmets 并将它们插入到每个 .panel div 中的表单中。
  • 似乎是在脚本执行之前加载了cmets...所以也许它与scrollHeight有关...

标签: jquery html css playframework


【解决方案1】:

您可以尝试将对.each 的调用封装在setTimeout 中,例如:

$(window).on('load', function() {
  setTimeout(function() {
    $(".panel").each(function (index) {
      alert(index);
      $(this).height($(this)[index].scrollHeight - 12);
    });
  }, 3000); // wait 3 seconds before executing
});

【讨论】:

  • 好主意,谢谢,但时间取决于加载了多少 div... 这不太好。
【解决方案2】:

我得到了答案,看来

$(this).height($(this)[index].scrollHeight

只是不起作用。

我不知道为什么,但是这样一切正常。

$(".panel .inputSizeLimitation").each(function () {
       $(this).height($(this).prop("scrollHeight") - 12);
    });

【讨论】:

    猜你喜欢
    • 2013-06-30
    • 2021-10-30
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多