结合函数 - jQuery

时间:2010-06-14 13:22:06

标签: javascript jquery jquery-ui

嘿伙计们我是JS的新手,我正在尝试组合我构建的一些功能并添加一些新的功能,但我有一个粗略的去。

<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", color: '#fff' }, 400);
});

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

我想要做的是通过组合它们来简化它们,并添加功能以在触发其中一个功能时折叠或撤消任何功能。到目前为止我很难过。

全部谢谢!

1 个答案:

答案 0 :(得分:0)

使用“包含”选择器整合内容:

        // 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);  
});

如果您想重置expand元素,我将如何处理它取决于您的HTML结构。

相关问题