【问题标题】:jQuery target id inside iframe and alertiframe 和警报中的 jQuery 目标 ID
【发布时间】:2017-07-07 21:30:16
【问题描述】:

我的代码如下。

<!DOCTYPE html>
<html>

  <head>
    <title>TODO</title>
  </head>

  <body>
    <div id="btn">
      <button id="clickme">Click Me</button>
    </div>
    <div class="iframebox">
      <iframe id="messageiframe">
        <html>

        <head>
          <title>test</title>
        </head>

        <body>
          <div id="textpreview">
            <p id="pre">some text</p>
          </div>
        </body>

        </html>
      </iframe>
    </div>
  </body>

</html>

我正在尝试使用 jQuery 在 iframe 中定位 id="textpreview"。我可以在 iframe 之外成功定位任何 id,但无法在 iframe 内定位。

我的 jQuery 代码是:

$('#clickme').on('click', function() {
  if ($("#textpreview").length > 0) {
    alert("success");
  }
});

我怎样才能做到这一点?

提前致谢。

【问题讨论】:

  • 你的 jquery 插件在哪里?

标签: jquery html iframe


【解决方案1】:

使用“内容()”

$("#messageiframe").contents().find("#textpreview")

https://api.jquery.com/contents/

【讨论】:

    【解决方案2】:

    <!DOCTYPE html>
    <html>
    
      <head>
        <title>TODO</title>
      </head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <body>
        <div id="btn">
          <button id="clickme">Click Me</button>
        </div>
        <div class="iframebox">
          <iframe id="messageiframe">
            <html>
    
            <head>
              <title>test</title>
            </head>
    
            <body>
              <div id="textpreview">
                <p id="pre">some text</p>
              </div>
            </body>
    
            </html>
          </iframe>
        </div>
      </body>
    <script>
    
    $('#clickme').on('click', function() {
    
      if ($("#textpreview").has("pre")) {
        alert("success");
      }
    });
    </script>
    </html>

    检查是否有id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多