【问题标题】:Adding IDs to DIV containers within an iFrame with jQuery使用 jQuery 将 ID 添加到 iFrame 中的 DIV 容器
【发布时间】:2021-01-24 21:50:48
【问题描述】:

我正在尝试使用 jQuery 将 ID 添加到 iFrame 中的 DIV 容器:

HTML 原文:

<iframe id="iFrame">
..
<div class="book-type">..</div>
<div class="book-type">..</div>
<div class="book-type">..</div>
..
</iframe>

HTML 修改:

<iframe id="iFrame">
..
<div class="book-type" id="type1">..</div>
<div class="book-type" id="type2">..</div>
<div class="book-type" id="type3">..</div>
..
</iframe>

我尝试使用以下脚本编辑 HTML,但它不起作用(正在运行但没有更改且没有错误),并且我不确定 each() 函数的正确选择器如何在 iframe 中工作(要修改的 DIV被包裹在几个 DIV 中,没有 ID,只有类)。

$(document).ready(function() {
    $('#iFrame').ready(function() {
        $('#iFrame').contents().find('div').each($('.book-type'), function(ind) {
            $(this).attr('id', 'type' + parseInt(ind + 1));
        });
    });
});

如果有人可以帮助我,我将非常感激!

【问题讨论】:

  • 另外,索引已经是一个整数。无需解析它。事实上,由于parseInt()函数expects a string,这可能会出错。
  • 没有变化,我在 JS 控制台中没有收到任何错误。我还用 alert() 替换了 counter 函数,但它没有被触发。因此,我怀疑每个()的选择器无法正常工作。

标签: javascript html jquery iframe


【解决方案1】:

您的选择器有问题可能是对的。简化为:

$('#iFrame').contents().find('.book-type').each(function(ind) {
    $(this).attr('id', 'type' + (ind + 1));
});

【讨论】:

    【解决方案2】:

    问题解决了!查询是否加载 iFrame 不起作用,因为 iFrame 不知道 ready() 而是 load()

    $(document).ready(function() {
        $('#iFrame').load(function() {
            $('#iFrame').contents().find('.book-type').each(function(ind) {
                $(this).attr('id', 'type' + (ind + 1));
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2012-07-14
      • 2016-07-14
      • 1970-01-01
      相关资源
      最近更新 更多