嘿大家好,我是 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/