簡體   English   中英

我可以改善此jQuery代碼重復嗎?

[英]Can I improve this jQuery code repetition?

我想學習有關jQuery的最佳實踐,以及如何避免重復代碼並使用優美的代碼。

我寫過:

<script type="text/javascript">
  // Change the category name with the filter
  $(function() {

    // Featured
    $('.featured').click(function() {
      $('.categoryTitle h1').hide().html('Featured').fadeIn('slow');
    });
    // Web
    $('.web').click(function() {
      $('.categoryTitle h1').hide().html('Web').fadeIn('slow');
    });
    // Brand
    $('.brand').click(function() {
      $('.categoryTitle h1').hide().html('Brand').fadeIn('slow');
    });
    // Print
    $('.print').click(function() {
      $('.categoryTitle h1').hide().html('Print').fadeIn('slow');
    });
    // All
    $('.all').click(function() {
      $('.categoryTitle h1').hide().html('All').fadeIn('slow');
    });
  });
</script>

的HTML

<ul id="filters">
    <li><a class="featured" href="#" data-filter=".feature-this">Featured</a></li>
    <li><a class="web" href="#" data-filter=".category-web">Web</a></li>
    <li><a class="brand" href="#" data-filter=".category-brand">Brand</a></li>
    <li><a class="print" href="#" data-filter=".category-print">Print</a></li>
    <li><a class="all" href="#" data-filter="*">Show All</a></li>
</ul>

<div class="categoryTitle"> <h1>Featured</h1> </div>

這是否盡其所能,還是我想念如何停止深入DOM?

注意我正在使用Isotope,一個jQuery插件。

編輯目前所有答案都沒有更改categoryTitle,但是我確實忽略了它的默認值Featured。

應該這樣做:

<script type="text/javascript">
$(function() {
    $('#filters').on('click', 'a', function() {
        $('.categoryTitle h1').hide().html($(this).text()).fadeIn('slow');
    });
});
</script>
function change(id){
$('.categoryTitle h1').hide().html(id).fadeIn('slow');
}

試試這個演示

<script type="text/javascript">
$(function() {
    $('#filters').on('click', 'a', function() {
        $(".categoryTitle").find("h1").hide().html($(this).text()).fadeIn('slow');
    });
});
</script>

就這么簡單:

  $('#filters a').click(function() {
        $('.categoryTitle h1').hide().html($(this).text()).fadeIn('slow');
  });
$(document).ready(function(){
   $('ul#filters li a').click(function(){
           $('.categoryTitle h1').hide().html($(this).text()).fadeIn('slow')

   });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM