从jquery数组值中选择div

时间:2012-12-17 19:52:25

标签: javascript jquery

我有一个简单的问题,我需要做一个动作.click()如果点击我的数组中的div ...

if($('#container_1').click(function(){ 
    $('div#image').fadeOut('fast', function(){
        $('div#cat_1').css('background-color', '#F30');
        $('#new_frame').show('fast').load('history.html');
    });
}));

if($('#container_2').click(function(){ 
    $('div#image').fadeOut('fast', function(){
        $('div#cat_2').css('background-color', '#F30');
        $('#new_frame').show('fast').load('history.html');
    });
}));

if($('#container_3').click(function(){ 
    $('div#image').fadeOut('fast', function(){
        $('div#cat_3').css('background-color', '#F30');
        $('#new_frame').show('fast').load('history.html');
    });
}));

if($('#container_4').click(function(){ 
    $('div#image').fadeOut('fast', function(){
        $('div#cat_4').css('background-color', '#F30');
        $('#new_frame').show('fast').load('history.html');
    });
}));

if($('#container_5').click(function(){ 
    $('div#image').fadeOut('fast', function(){
        $('div#cat_5').css('background-color', '#F30');
        $('#new_frame').show('fast').load('history.html');
    });
}));

好的,这是我的代码有效...

但我认为我可以做得更短......用这样的代码::

Contenedores = ['1', '2', '3', '4', '5'];

if($('#container_'+Contenedores).click(function(){ 
    $('div#image').fadeOut('fast', function(){
        $('div#cat_'+Contenedores).css('background-color', '#F30');
        $('#new_frame').show('fast').load('history.html');
    });
}));

但我不知道如何正确地工作......

谢谢,对不起我的英语很差。

3 个答案:

答案 0 :(得分:4)

我只是使用被点击元素的ID中的数字来获取“cat”元素。为什么你会做同样的事情并在每次点击时加载相同的内容超出我的范围,但是这样的事情:

$('[id^="container_"]').on('click', function(){ 
    var self=this;
    $('div#image').fadeOut('fast', function(){
        $('div#cat_'+self.id.replace('container_','')).css('background-color', '#F30');
        $('#new_frame').show('fast').load('history.html');
    });
});

答案 1 :(得分:2)

有很多方法可以执行此操作,您也可以将值分隔为逗号:

$('#container_1,#container_2,#container_3,#container_4,...').click(function(){ ...

或者您可以在这些div上使用类名来使其更简单:

$('.toclick').click(function(){

});

使用班级名称将是我的最爱。

PS:你不需要if语句。

答案 2 :(得分:0)

你只需循环遍历你的数组:

var Contenedores = ['1', '2', '3', '4', '5'];

$.each(Contenedores,function(index,value){
$('#container_'+value).click(function(){ 
$('div#image').fadeOut('fast', function(){
    $('div#cat_'+value).css('background-color', '#F30');
    $('#new_frame').show('fast').load('history.html');
});
});
});

尽管如此,必须有更好的方法 - 无论是课程还是事件授权 - 但如果不了解您的用例,很难说清楚。