开发者

Combining functions - jQuery

Hey guys I'm new to JS and I'm trying to combine some functions I built and add some new functionality, but I'm having a rough go.

<script>
$(".1trigger").click(function () {
$(".1expand").toggle("blind", 100);
});

$(".2trigger").click(function () {
$(".2expand").toggle("blind", 100);
});

$(".3trigger").click(function () {
$(".3expand").toggle("blind", 100);
});

$(".4trigger").click(function () {
$(".4expand").toggle("blind", 100);
});
</script>

<script>
$(".1trigger").toggle(function() {
 $(this).animate({ backgroundColor: "#fff", color: '#FD0E35'}, 400);},function() {
    $(this).animate({ backgroundColor: "#FD0E35", color: '#fff' }, 400);  
});

$(".2trigger").toggle(function() {
    $(this).animate({ backgroundColor: "#fff", color: '#00c260'}, 400);
},function() {
    $(this).animate({ backgroundColor: "#00c260", co开发者_Go百科lor: '#fff' }, 400);
});

$(".3trigger").toggle(function() {
    $(this).animate({ backgroundColor: "#fff", color: '#1f293f'}, 400);
},function() {
    $(this).animate({ backgroundColor: "#1f293f", color: '#fff' }, 400);
});
</script>

What I want to do is simplify these by combining them and also add the functionality to collapse or undo any of the functions when another one of these is triggered. I'm having a hard time so far.

Thanks all!


Use the "contains" selector to consolidate things:

        // Bind to all elements that have a class containing the word trigger
$("[class*=trigger]").click(function () {

       // Get the number from the trigger class
    var number = $(this).attr('class').match(/(\d+)trigger/)[1];

       // Concatenate that number into the expand class selector
    $("." + number + "expand").toggle("blind", 100);
});

       // Store your colors in an array
       // You may want to use classes to hold your colors instead
var colorsArray = ["#FD0E35",
                   "#00c260",
                   "#1f293f"
                  ];

        // Bind to all elements that have a class containing the word trigger
$("[class*=trigger]").toggle(function() {

       // Get the number from the trigger class
    var number = $(this).attr('class').match(/(\d+)trigger/)[1];

       // Based on the number, get the proper color from the colorsArray
    $(this).animate({ backgroundColor: "#fff", color: colorsArray[number - 1]}, 400);
},
function() {

       // Same as above
    var number = $(this).attr('class').match(/(\d+)trigger/)[1];
    $(this).animate({ backgroundColor: colorsArray[number - 1], color: '#fff' }, 400);  
});

If you want to reset the expand elements, how I would go about it would depend on your HTML structure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜