是否可以在jquery中为不同的选择器组合这样的函数?

时间:2011-02-22 17:32:59

标签: jquery

jquery只是另一个愚蠢的想法。是否可以在Jquery中执行类似的操作:

而不是像这样输入所有三个:

$('#id1').click(function(){
$('#idanother1').animate({height:'100px'},450);
$('#id1').toggleClass('my-added-class');
});

$('#id2').click(function(){
$('#idanother2').animate({height:'100px'},450);
$('#id2').toggleClass('my-added-class');
});

$('#id3').click(function(){
$('#idanother3').animate({height:'100px'},450);
$('#id3').toggleClass('my-added-class');
});

我希望能够写出类似这样的内容:

$('#id1' / '#id2' / '#id3').click(function(){
$('#anotherid1' / '#anotherid2' / '#anotherid3').animate({height:'100px'},450);
$('#id1' / '#id2' / '#id3').toggleClass('my-added-class');
});

如果我不想将类添加到id2,我只需将它排除在外:

$('#id1' / '' / '#id3').toggleClass('my-added-class');

3 个答案:

答案 0 :(得分:1)

您需要idxanotheridx之间的映射,然后才能使用multiple selector。例如:

var map  = {
    'id1': $('#anotherid1'),
    'id2': $('#anotherid2'),
    'id3': $('#anotherid3')
};

$('#id1, #id2, #id3').click(function(){
    map[this.id].animate({height:'100px'},450);
    $(this).toggleClass('my-added-class');
});

也就是说,如果你有更多元素,你应该给它们一个类,这样你就可以只按类名选择所有元素。

如果您能够在元素idxanotheridx之间找出另一个关系而不必维护显式映射,那也会更好。

但是如果您在点击处理程序中需要不同的功能,则根据单击的元素,您必须使用单独的事件处理程序。但是,您可以识别注释功能并将其放入自己的函数中,并从处理程序中调用它:

function commenHandler() {
    map[this.id].animate({height:'100px'},450);
    // potentially more code...
}

$('#id1, #id3').click(function(e){
    commenHandler.call(this, e);
    $(this).toggleClass('my-added-class');
});

$('#id2').click(commenHandler);

答案 1 :(得分:0)

这是正确的选择器语法:

$('#id1 , #id2 , #id3').click(function(){...

请参阅JQuery selector文档。

答案 2 :(得分:0)

如果您完全依赖于通过结尾号码链接的ID的明显惯例,您可以尝试这样的事情:

var targets = [
  '#id1',
  '#id2',
  '#id3'
];

$(targets.join(',')).click(function(){
  var relatedid = this.id.replace(/(.*\D)(\d+)/i,'$2');
  $('#idanother' + relatedid).animate({height:'100px'},450);
  $(this).toggleClass('my-added-class');
});