jquery每个函数给出值0

时间:2014-08-21 19:15:44

标签: jquery load each

我在jquery中有一个脚本,它通过检查iframe的内容高度来设置iframe高度。但它设置了两个iframe上第一个iframe内容高度的高度。

jQuery(document).ready(function($){

  $("iframe").load(function() {
    var iframeHeight = $("iframe").contents().height();
    $("iframe").height(iframeHeight);
  });

});

更改为“each functions”而不是“load”会生成值0。

jQuery(document).ready(function($){

  $("iframe").each(function() {
    var iframeHeight = $("iframe").contents().height();
    $("iframe").height(iframeHeight);
  });

});

为什么每个功能都不起作用?

由于

马格努斯

更新 谢谢你的快速解答!这是一个带有附加iframe的标签解决方案。

我为隐藏(display:none)iframe的标签添加了一个点击功能。我几乎可以工作......

当我点击“第二个”标签时,它不会在第一次点击时改变iframe的高度!但是,如果我第二次单击相同的标签,我将高度更改为iframe内容。为什么呢?

<script type="text/javascript">
jQuery(document).ready(function($) {

     $("iframe").load(function() {
          var iframeHeight = $(this).contents().height()
          $(this).height(iframeHeight);
          console.log(iframeHeight);
     });

     $(".tab").click(function() {
          $(".current_tab .iframe").css("display","block");
          var iframeHeight = $(".current_tab .iframe").contents().height()
          $(".current_tab .iframe").height(iframeHeight);
          console.log(iframeHeight);
     });

});
</script>

2 个答案:

答案 0 :(得分:1)

尝试在函数

中使用“this”而不是“iframe”
jQuery(document).ready(function($){

  $("iframe").load(function() {
    var iframeHeight = $(this).contents().height();
    $(this).height(iframeHeight);
  });

});

那应该有用

答案 1 :(得分:0)

我不确定这是一个很好的解决方案。但这就是我最终的结果。

<script type="text/javascript">
jQuery(document).ready(function($) {

     $("iframe").load(function() {
          var iframeHeight = $(this).contents().height()
          $(this).height(iframeHeight);
          console.log(iframeHeight);
     });

    $(document).on("click",".tab",function(){
          $(".current_tab .iframe").css("display","block");
          var iframeHeight = $(".current_tab .iframe").contents().height()
          $(".current_tab .iframe").height(iframeHeight);
          console.log(iframeHeight);
     });

});
</script>

随意发表评论。

由于