是否可以在jquery中为不同的选择器组合这样的函数? [英] Is it possible to combine functions for different selectors like this in jquery?

查看:69
本文介绍了是否可以在jquery中为不同的选择器组合这样的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jquery只是另一个愚蠢的想法。是否有可能在Jquery中做这样的事情:

Just another silly thought for jquery. Is it possible to do something like this in Jquery:

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

Instead of typing all three like this:

$('#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');
});

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

I would like to be able to write it something like this:

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

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

And if I don’t want to add class to id2 I simply exclude it like this:

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


推荐答案

您需要之间的映射idx anotheridx 然后你可以使用 多个选择器 。示例:

You need a mapping between idx and anotheridx and then you could use the multiple selector. Example:

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');
});

这就是说,如果你有更多的元素,你应该给他们一个类,这样你就可以选择所有元素都只是通过类名。

That said, if you have more elements, you should give them a class, so that you can select all elements just by the class name.

如果你能在元素之间找出另一个关系也会更好 idx anotheridx 无需维护显式映射。

It would also be better if you could figure out another relation between the elements idx and anotheridx to not have to maintain an explicit mapping.

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

But if you need differently functionalities in the click handler, depending on which element was clicked, you have to use separate event handlers. You can, however, identify the comment functionality and put it into its own function and call this one from the handlers:

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

这篇关于是否可以在jquery中为不同的选择器组合这样的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆