我想学习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。
邮政ÿ我们的'html'部分也是 – coolguy
是的,清理的一部分需要在你的HTMl中。张贴也是。 – techfoobar