在jquery上做这件事的最短路径是什么?

时间:2012-01-01 16:14:09

标签: javascript jquery

这是我拥有的,它的工作原理很好,但是你能否告诉我是否有任何简短的编码方式来做到这一点?

$(document).ready(function() {  
    $('span#paylas_').click(function() {
        $('#uyri').slideUp();
        $('#dhda').slideUp();
        $('#pyls').slideToggle('normal');
    });
    $('span#uyari_').click(function() {
        $('#pyls').slideUp();
        $('#dhda').slideUp();
        $('#uyri').slideToggle('normal');
    });
    $('span#dahada_').click(function() {
        $('#pyls').slideUp();
        $('#uyri').slideUp();
        $('#dhda').slideToggle('normal');
    });     
});

4 个答案:

答案 0 :(得分:6)

如果您为此元素提供data-toggle属性,请执行以下操作:

<span id="paylas_" data-toggle="#pyls"></span>

然后你可以组合选择器并使用.data("toggle")来获得适当的选择器:

$(document).ready(function() {
    var toggles = {};

    $('#paylas_, #uyari_, #dahada_').click(function() {
        var cached = this.id in toggles;

        if(!cached) {
            toggles[this.id] = $(this).data("toggle");
        }

        var toggle = toggles[this.id];

        $('#uyri, #dhda, #pyls').not(toggle).slideUp();
        $(toggle).slideToggle('normal');
     });
});

如果仅对这些元素使用data-toggle,那么您也可以这样做:

$('[data-toggle]').click(function() {

我无法真正构建ID,但如果有某种结构,你也可以推广第二个选择列表。

答案 1 :(得分:2)

$(function() {//notice the shorter document.ready declaration :)

    //setup a conversion from the clicked elements to the elements to slide up/down
    var convert = {
        paylas_ : '#pyls',
        uyari_  : '#uyri',
        dahada_ : '#dhda'
    };

    //select all the spans and bind the event handler to them, you can select multiple elements at once by separating the selectors with commas
    $('#paylas_, #uyari_, #dahada_').click(function() {

        //slide up all the spans except for the on associated with the currently clicked element
        $('#uyri, #dhda, #pyls').not(this).slideUp();

        //slide toggle the currently clicked element
        $(convert[this.id]).slideToggle('normal');
    });  
});

以下是演示:http://jsfiddle.net/yPxHq/1/

答案 2 :(得分:2)

我认为这是没有链接HTML的最简洁方法:

$(document).ready(function() {
    $("#paylas_, #uyari_, #dahada_").click(function() {
        var ids = ["#uyri", "#dhda", "#pyls"],
        current = "#" + $(this)
            .attr("id")
            .replace(/_$/, "")
            .replace(/a(.)/g, "$1");
        delete ids[$.inArray(current, ids)];
        $(ids.join(",")).slideUp();
        $(current).slideToggle("normal");
    });
});

修改:已删除前面的span

答案 3 :(得分:1)

这是一个快速的重构,可能有点帮助

 $(document).ready(function() {
            clickFuntion("paylas","uyri","dhda","pyls");
            clickFuntion("uyari","pyls","dhda","uyri");
            clickFuntion("dahada","pyls","uyri","dhda");

            function clickFuntion(var1,va2,var3,var4){
             $('span#"+var1+"_').click(function() {
                $('#"+var2+"').slideUp();
                $('#"+var3+"').slideUp();
                $('#"+var4+"').slideToggle('normal');
            });

            }
    });