javascript - 组合函数 - jQuery

标签 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>

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

谢谢大家!

最佳答案

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

        // 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 结构。

关于javascript - 组合函数 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3037519/

相关文章:

javascript - 文本框中的 onchange 事件不起作用

javascript - 对 NodeJS 服务器的超慢发布请求

javascript - mocha-phantomjs 错误加载资源 mocha.js

jQuery:选择器在同一属性上使用 'logical AND'

jquery - 是否可以使用按键(PgUp、PgDn、...空格键?...)来控制可滚动的 jquery ui 对话框

jquery - 关闭 jQuery Accordion 自动调整大小

javascript - 如何使用 jquery ui slider 更改 div 的类

javascript - 使用 AngularJS 尝试在中间插入一个 <tr>

javascript - 本地主机的 Google map api 使用

jquery - 抓取网站|如何创建 JSON 文件?