【问题标题】:get text javascript + iframe获取文本 javascript + iframe
【发布时间】:2014-01-02 17:47:12
【问题描述】:

我有html代码

网站索引.html

<html>
<body>
  <iframe id="html2" frameborder="0" src="html2.htm" marginwidth="0" marginheight="0" style="height: 492px;"></iframe>
</body>
</html> 

网站 html2.htm

<html>
<body>
  <div><p id='123'>hello</p></div>
</body>
</html>

当我在站点 index.html 中使用 document.getElementById('123') return = null; 我怎么能得到它

【问题讨论】:

  • 可能重复:stackoverflow.com/questions/1088544/… 另外,id 不能以数字开头,如果 iframed 页面位于不同的域中,这将根本不起作用。
  • 欢迎新用户。跟我去后街吧。我会告诉你一个小技巧:stackoverflow.com/tour
  • @m59 你扼杀了我缩进代码的冲动。谢谢。
  • @MilchePatern 嗯?我很着迷,哈哈。

标签: javascript html iframe


【解决方案1】:

您需要先通过以下方式访问 iframe 的 innerDoc:

var iframe = document.getElementById('html2');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

一旦你得到了对象,现在你就可以访问了:

innerDoc.getElementById('divId');

对于html中的ID,需要遵循以下规则:

ID 应该匹配:

[A-Za-z][-A-Za-z0-9_:.]*
  1. 必须以 A-Z 或 a-z 字符开头
  2. 可能包含 _(连字符)、:(colan) 和 .(dot)

但应该避免使用: 和.,因为 jQuery 选择器会与类和过滤器发生冲突。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2011-09-15
    • 1970-01-01
    相关资源
    最近更新 更多