如何避免此jQuery代码中的重复代码? [英] How can I avoid the repetitive code in this jQuery code?

查看:299
本文介绍了如何避免此jQuery代码中的重复代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个网站,这段代码让我在1 .html文件中有几个页面。可以避免此代码的迭代性吗?可以简化吗?

I am making a site and this code lets me have several pages in 1 .html file. Can the iterative-ness of this code be avoided? Can it be simplified?

<script type="text/javascript">
        var x = 300;
        $(function() { 
            $("#indexLink").click(function() { 
                $("#content>div").not("#start").hide(x);
                $("#index").show(x);
                $('nav>ul>li').removeClass('active');
                $('#indexLink').addClass('active');
            });

            $("#leerlingLink").click(function() { 
                $("#content>div").not("#start").hide(x); 
                $("#leerling").show(x); 
                $('nav>ul>li').removeClass('active');
                $('#leerlingLink').addClass('active');
            });

            $("#bestemmingLink").click(function() { 
                $("#content>div").not("#start").hide(x); 
                $("#bestemming").show(x);
                $('nav>ul>li').removeClass('active');
                $('#bestemmingLink').addClass('active');
            });

            $("#betalingLink").click(function() { 
                $("#content>div").not("#start").hide(x); 
                $("#betaling").show(x);
                $('nav>ul>li').removeClass('active');
                $('#betalingLink').addClass('active');
            });
        });

</script>


推荐答案

你是什么意思 iterative-ness

如果你想让你的代码干,你可以写下这样的东西:

if you want your code to be DRY you could just write somthing like this:

<script type="text/javascript">
    var x = 300;
    $(function () {
        $("#indexLink,#betalingLink,#bestemmingLink,#leerlingLink").click(function () {
            $("#content>div").not("#start").hide(x);
            $("#"+$(this).attr("id").slice(0,-4)).show(x);
            $('nav>ul>li').removeClass('active');
            $('#indexLink').addClass('active');
        });
    });
</script>

这将占用所有选择器,当时一个,并使所有选择器运行您的代码,与您输入的基本相同,但只在一个选择器中

this will take all selectors, one at the time, and make all of them run that code of yours, basically the same as you typed, but in one selector only

编辑

修正div显示

EDIT2

添加了jsfiddle以显示它正常工作:< a href =http://jsfiddle.net/NicosKaralis/Vurjf/ =nofollow> http://jsfiddle.net/NicosKaralis/Vurjf/

added jsfiddle to show it working: http://jsfiddle.net/NicosKaralis/Vurjf/

这篇关于如何避免此jQuery代码中的重复代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆