【问题标题】:jquery find all the matching elements inside a container including the iframe elementsjquery 查找容器内的所有匹配元素,包括 iframe 元素
【发布时间】:2022-01-11 09:48:22
【问题描述】:
<div id="container">
<div tabindex="0">Tabbable content 1</div>
<div>Non Tabbable content 2</div>
<button type="submit">Submit</button>
<label>First Name: <input type="text" /></label>
<iframe height="600" width="600" src="iframe.html"></iframe>
</div>


Iframe.html
<label>Last Name: <input type="text" /></label>
<div tabindex="0">Tabbable content inside iframe</div>

我想在容器[tabindex="0"],a,input,select,button 中找到与此选择器匹配的所有元素。

预期输出:Tabbable Content 1buttonFirst Name inputlast name inputTabbable content inside iframe 应返回元素。

我试过 $('[tabindex="0"],a,input,select,button', $('#container')), document.querySelector('#container').querySelectorAll('[tabindex= "0"],a,输入,选择,按钮')

【问题讨论】:

  • 大部分都将按预期工作。要同时添加 iframe 中的元素,您必须获取 iframe 元素的内容。

标签: javascript html jquery iframe


【解决方案1】:

考虑以下问题:https://jsfiddle.net/Twisty/hzpvxowc/

JavaScript

$(function() {
  var myElems = $('[tabindex], a, input, select, button', "#container").add($('[tabindex], a, input, select, button', $("iframe").contents()));
  console.log(myElems.length);
});

这在控制台中显示5,这是预期的。

查看更多:https://api.jquery.com/add/

【讨论】:

  • 有没有办法获取 iframe 的内容?在我的实际场景中,iframe 内容是从跨域呈现的,当我尝试访问 iframe 内容时,我得到Blocked a frame with origin
  • @codegig 非常怀疑。这是一个 CORS 问题。
【解决方案2】:

如果你想从 iframe 中选择元素,首先你应该选择 iframe 的内容,然后在框架的内容中找到目标元素。例如,假设我们有一个 id 为 frm1 的 iframe,我们想要选择 frame 中的所有输入:

$("#frm1").contents().find("input");

let iframe= $("#frm1");
$('input', iframe.contents());

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2010-09-24
    相关资源
    最近更新 更多