javascript - 如何允许iframe访问Element.prototype

标签 javascript

我已经创建了诸如 hasClass() 之类的原型(prototype),因此我可以调用 e.target.hasClass('className');。现在,当我调用原型(prototype)时它可以工作,但是我的页面上有一个 iframe,当我在页面构建器上工作时,我一直进出该 iframe。但是,如果我引用 iframe 中的元素,则该元素不存在原型(prototype)函数。

如何让 Element.prototype 函数在父级和 iframe 中工作?

最佳答案

您需要访问加载事件处理程序内的 iframe 窗口,并且可以执行如下操作:

var frame = document.getElementById('ifrm');
frame.onload = function() {
  var win = this.contentWindow || this.contentDocument;
  win.Element.prototype.test = function() {
    this.innerHTML = 'Iframe Prototype content'
  }
  win.document.getElementById('heading').test()

}

因此,如果您要将所有新原型(prototype)属性包装到一个函数中,您可以在主窗口上下文和框架窗口上下文中调用该函数

DEMO

关于javascript - 如何允许iframe访问Element.prototype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694268/

相关文章:

javascript - jQuery秒表,计算平均值并显示

javascript - 使用 Angular Router 获取 URL

javascript - 获取分配给变量函数的名称

javascript - Node.js 0.12 中提供的 ECMAScript 6 功能

javascript - React js 状态未在表单上设置

javascript - 在javascript中选择一行后如何取消选择其他行?

php - JavaScript 与 PHP : The same calculation returns different result

javascript - 冲突的 jQuery/JavaScript?

javascript - 悬停一个 div 并使用 JS 在具有 3 行的表中的同一行内使用相同的类修改另一个 div 的 CSS

javascript - 防止ajax中的特殊字符(http)