2011-02-22 93 views
1

另一个愚蠢的想法为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'); 

回答

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); 
+0

这就是爽!谢谢。 – Hakan 2011-02-22 18:09:27

0

使用逗号和通用fu nction。

$("#id1, #id2, #id3").click(function(){ 
    var $t = $(this); //this caches object 
    var myNo = $t.attr("id").replace("id",""); 

    $("#anotherID"+myNo).animate({height:'100px'},450); 

    // filter out unwanted IDs 
    if (myNo !== "2") { 
     $t.toggleClass('my-added-class'); 
    } 
}); 

你得到什么独特的ID(myNo),用它来制作动画相应anotherID,然后通过唯一的ID号/短语(再次myNo)来判断,过滤掉你不想要的,然后在第一个位置切换任何DOM元素被点击的类。

0

这是一个正确的选择语法:

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

见JQuery的selector文档。

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'); 
}); 
相关问题