2012-09-21 42 views
1

我想学习jQuery的最佳实践,以及如何避免代码复用并使用优雅的代码。我可以改进这个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。

+2

邮政ÿ我们的'html'部分也是 – coolguy

+0

是的,清理的一部分需要在你的HTMl中。张贴也是。 – techfoobar

回答

1

试试这个demo

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

我认为这不起作用,因为它似乎并不是'h1'是'$(this)'的子元素。 – insertusernamehere

+1

抱歉代码错误。更新 。现在应该工作 – Champ

+0

这不是更新categoryTitle – SMacFadyen

1
function change(id){ 
$('.categoryTitle h1').hide().html(id).fadeIn('slow'); 
} 
6

这应做到:

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

不幸的是,它没有得到#filters a – SMacFadyen

+0

的文字哦?奇怪。我有[在这个小提琴上工作](http://jsfiddle.net/r7Ncm/)。请注意,我添加了'e.preventDefault()' - 如果您愿意,您可以将其保留,但它会停止URL的默认附加'#'字符(片段)。 –

+0

categoryTitle h1的默认值为推荐 – SMacFadyen

0

这是像这样简单:

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

    }); 
});