【问题标题】:Add or Remove Attribute using jQuery toggle to Hide / Show an item使用 jQuery 切换添加或删除属性以隐藏/显示项目
【发布时间】:2013-04-30 15:45:38
【问题描述】:

我有以下 jQuery,当我单击按钮时,我使用它来隐藏/显示 iFrame。

iFrame 包含一些 PHP,我只想在 iFrame 显示时加载。

$(document).ready(function()
    {
        $('#button').click(function()
            {
                $('#graphFrame').toggle().attr('src', 'graph1.php');    
            }
        )   
    }
);

这很好用,除了当我隐藏 iFrame 时它还会尝试加载 PHP。

有没有办法告诉它在我显示 iFrame 时添加 'src' 属性(从而加载 php),并在我隐藏 iFrame 时删除它(从而不加载 PHP)?

【问题讨论】:

    标签: jquery toggle attr


    【解决方案1】:

    试试

    $('#graphFrame').toggle(function(){
         var $this = $(this);
        $this.is(":visible") ? $this.attr('src', 'graph1.php') : $this.removeAttr('src')
    });
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $(document).ready(function () {
          $('#button').click(function () {
              $('#graphFrame').toggle();
              $('#graphFrame:visible').attr('src', 'graph1.php');
          });
      });
      

      【讨论】:

        【解决方案3】:

        你可以试试这个

        $('#button').click(function(){
            var ifr = $('#graphFrame');
            ifr.toggle(function(){
                if(ifr.is(':visible')) ifr.attr('src', 'graph1.php');
                else ifr.attr('src', '');
            });
        });
        

        DEMO.

        【讨论】:

        • 谢谢,我特别喜欢这个让图表滑入视野的事实。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        • 1970-01-01
        相关资源
        最近更新 更多