【问题标题】:Javascript date picker error in iframeiframe 中的 Javascript 日期选择器错误
【发布时间】:2017-12-16 15:49:09
【问题描述】:

我有一个页面 https://dev.leadformly.com/datepicker 有一个 iframe 在那个特定的''中,我正在通过以下代码的ajax调用动态编写HTML代码。

<script>
  $(document).ready(function(){
    $.post(URL,
        function (data) { //here it retruns the HTML code
          $("body").html('<iframe style="width:100%;height:384px;"></iframe>');
          $("body iframe")[0].contentDocument.write(data.democode);
        },
        'json'
      );
    });
</script>

现在,当我单击日期选择器时,它会在控制台中引发错误,例如:

Uncaught TypeError: Cannot read property 'top' of undefined

你能帮我解决这个问题吗?或者只是解释原因,以便帮助我解决它

【问题讨论】:

  • 您使用的是哪个日期选择器?
  • 默认 jquery datepicker - jqueryui.com/datepicker
  • 这个错误好像是在DateRangePicker中遇到的,不是jQuery datepicker。你能仔细检查一下吗?
  • 这是 Bootstrap "daterangepicker" 而不是 jquery,对此感到抱歉。
  • 为什么你仍然在这里使用 iframe?您正在加载不同的 url,那么在这里使用 iframe 有什么好处?

标签: javascript jquery html iframe bootstrap-daterangepicker


【解决方案1】:

您收到此错误是因为您尝试从包含它的父 DOM 访问 iFrame 的内部 DOM。来自父 DOM 的“点击”事件无法调用子 iFrame 中的元素。

请问您为什么在这种情况下尝试使用iFrame?我几乎可以向你保证,最好不要使用它。

【讨论】:

    【解决方案2】:

    您的最后一个选择是尝试使用沙盒属性。

    allow-scripts: Allows the embedded browsing context to run scripts (but not create pop-up windows). If this keyword is not used, this operation is not allowed.

    https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe

    如果这不起作用,请远离 iframe。 iframe 元素被创建为沙盒环境,当您打开允许脚本时,很容易出现非常高的安全风险。如果您删除沙盒,则放入 iframe 中的生成网页/外部站点可以做任何事情......从获取凭据、cookie、访问等几乎任何事情。

    如果您想在其内容中访问 DOM,强烈建议不要使用 Iframe。如果您只关心完全或部分隔离,请尝试使用 Web 组件的隔离方法:

    https://developer.mozilla.org/en-US/docs/Web/Web_Components

    【讨论】:

      【解决方案3】:

      我认为 jQuery 无法读取 iframe 元素,这就是它显示的原因 Cannot read property top of undefined 错误。

      在 iframe 元素中使用 id="ifreame" 即可。

      <iframe id="ifreame" style="width:100%;height:384px;"></iframe>
      

      jQuery

      $("body #iframe")[0].contentDocument.write(data.democode);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多