用jquery更改iframe src

时间:2017-04-30 08:00:59

标签: javascript jquery iframe

我正在尝试更改我的iframe src并使用以下代码重新加载iframe

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
  $('#changeframe').click(function () {
  $('#declinedframe').attr('src', 'http://stackoverflow.com');
  });
</script>


<input type="button" id="changeframe" value="Change">

<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%" ></iframe>

当我点击按钮上的“更改”时,没有任何反应。我做错了什么?

2 个答案:

答案 0 :(得分:4)

订单很重要。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="button" id="changeframe" value="Change">

<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%" ></iframe>

// Go Last since changeframe hasn't exist yet.
<script>
  $('#changeframe').click(function () {
      $('#declinedframe').attr('src', 'http://stackoverflow.com');
  });
</script>

答案 1 :(得分:0)

  1. 如果代码与示例中的代码相同,则需要将jQuery包装在中 $(function() { ... });或将其移至html以下的按钮 脚本运行时不存在
  2. 查看控制台。您可能不被允许更改包含来自其他域的URL的iframe的src - 某些浏览器(如IE)可能会引发安全性异常。您可以在控制台中拒绝访问
  3. 某些网站不允许对其网页进行框架处理。在您的示例中并非如此,但如果您尝试在框架中加载Google,则会出现错误
  4. &#13;
    &#13;
    $(function() {
      $('#changeframe').click(function() {
        $('#declinedframe').attr('src', 'http://stackoverflow.com');
      });
    });
    &#13;
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    
    <input type="button" id="changeframe" value="Change">
    
    <iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%"></iframe>
    &#13;
    &#13;
    &#13;

    使用链接 - 不需要jQuery(如果上面的按钮提交表单,目标iframename,则相同):

    &#13;
    &#13;
    <a href="http://stackoverflow.com/" target="declinedframe">Change</a>
    
    <iframe name="declinedframe" id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%"></iframe>
    &#13;
    &#13;
    &#13;

    如果你必须使用jQuery作为链接,请给它改变框架的ID

    $(function() {
      $('#changeframe').on("click",function(e) {
        e.preventDefault(); // cancel the link
        $('#declinedframe').attr('src', this.href );
      });
    });