【问题标题】:Create and remove div in jQuery and Rails在 jQuery 和 Rails 中创建和删除 div
【发布时间】:2015-01-28 18:26:20
【问题描述】:

在我的网站上,我有不同艺术家的不同盒子,每个盒子上都有一个播放按钮来加载 Spotify 播放器。

我习惯这样做:

$(document).ready(function(){$(".playid-"+#{artist.id.to_s}).click(function () {
$(".player-id-"+#{artist.id.to_s}).fadeToggle()
;}

工作正常。但是,当我单击第二个/第三个...播放按钮时,播放器的 div 会一次又一次地创建。

我想要的是检查 div 是否存在,然后隐藏/销毁/删除,然后创建播放器的新 div,这样我随时只创建 1 个 div。

我已尝试使用 .remove,但我不知道使用相同代码创建新 div 的正确方法:

%div{:class => 'player player-id-'+artist.id.to_s}
  %iframe{:src => 'https://embed.spotify.com/?uri='+artist.spotify_player_url, :width => "100%", :height => "80px", :frameborder => "0", :allowtransparency => "true", :class => "player_spotify"  }

谢谢!

【问题讨论】:

    标签: javascript jquery ruby-on-rails haml


    【解决方案1】:

    在显示新元素之前隐藏所有player 元素怎么样?

    $(document).ready( function(){
      $(".playid-"+#{artist.id.to_s}).click(function () {
        $(".player").fadeOut();
        if( $(".player-id-"+#{artist.id.to_s}).is(':hidden') ) {
          $(".player-id-"+#{artist.id.to_s}).fadeIn();
        }
      }
    });
    

    【讨论】:

    • 您好,谢谢。这样可以很好地创建和销毁,但是当我再次单击播放按钮时,再次加载播放器而不是隐藏它,我需要它,就像使用 .fadeToggle() 属性一样。如果我点击播放一次fadeIn,但如果我第二次点击同一播放器是FadeOut。
    • 谢谢@antyrat 我添加了正确的代码并回答。和你的非常相似!谢谢!!
    【解决方案2】:

    如果有人需要,这是正确的代码。非常感谢antyrat

    $(document).ready( function(){
    $(".playid-"+#{artist.id.to_s}).click(function () {
    $(".player").fadeOut();
    if(!$(".player-id-"+#{artist.id.to_s}).is(":visible")) {
    $(".player-id-"+#{artist.id.to_s}).fadeIn();
    }
    }
    )
    ;}
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-03
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      相关资源
      最近更新 更多