0

jquery を使用して、一部のクラスの表示プロパティ (オンとオフ) を切り替えようとしています。

クリックで切り替えるために、画像と下のテキストを交換しようとしています

<div class="fab red off">
    <img class="community_service_icon" src="http://placehold.it/50x50">
    <div class="community_service_text">
        Charity Run<br/>
        Charity Sale<br/>
        Bake Sale<br/>
        Photo Exhibition<br/>
    </div>
</div>

ここに私のjquery関数があります:

jQuery(function($) {
  $('.fab.red.off').click(function() {
    $(this).removeClass( 'off' ).addClass( 'on' );
    $(this).children( '.community_service_icon' ).css('display', 'none');
    $(this).children( '.community_service_text' ).css('display', 'block');
  });
});

jQuery(function($) {
  $('.fab.red.on').click(function() {
    $(this).removeClass( 'on' );
    $(this).addClass( 'off' );
    $(this).children( '.community_service_icon' ).css('display', 'block');
    $(this).children( '.community_service_text' ).css('display', 'none');
  });
});

最初のクリックで画像が非表示になり、テキストが表示されます。また、クラスが「fab red on」に変更されます。ただし、fab div をもう一度クリックすると、セレクター '.fab.red.off' で最初の関数が実行されているように見え、他の関数はトリガーされません。

何か案は?また、このコードを最適化するための提案も大歓迎です。

乾杯

4

4 に答える 4

4

を使用してコードを簡素化できます.toggle()。これにより、要素が表示されている場合は非表示になり、表示されていない場合は表示されます。

jQuery(function($) {
  $('.fab.red').click(function() {
    $(this).find('.community_service_icon').toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="fab red">
  <img class="community_service_icon" src="http://placehold.it/50x50">
  <div class="community_service_text">
    Charity Run
    <br/>Charity Sale
    <br/>Bake Sale
    <br/>Photo Exhibition
    <br/>
  </div>
</div>

于 2015-01-05T07:43:16.350 に答える
1

$('.fab.red').click(function() {
  $(this).toggleClass('off');
});
.off img {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="fab red">
  <img class="community_service_icon" src="http://placehold.it/50x50">
  <div class="community_service_text">Charity Run
    <br/>Charity Sale
    <br/>Bake Sale
    <br/>Photo Exhibition
    <br/>
  </div>
</div>

于 2015-01-05T07:47:25.187 に答える
0

Use .on() function as follows docs

jQuery(function($) {
    $(document).on('click', '.fab.red.off', function() {
    $(this).removeClass( 'off' ).addClass( 'on' );
    $(this).children( '.community_service_icon' ).css('display', 'none');
    $(this).children( '.community_service_text' ).css('display', 'block');
  });
});

jQuery(function($) {
  $(document).on('click', '.fab.red.on', function() {
    $(this).removeClass( 'on' );
    $(this).addClass( 'off' );
    $(this).children( '.community_service_icon' ).css('display', 'block');
    $(this).children( '.community_service_text' ).css('display', 'block');
  });
});

Working Fiddle

于 2015-01-05T07:43:48.070 に答える