How can I simplify this jquery?

I have the following jquery that I want to simplify.

I'm just repeating the same thing.

Can someone please give me suggestions.

Thanks in advance.

$("a[rel='imagebox-all']").colorbox({slideshow:true});
$("a[rel='imagebox-new']").colorbox({slideshow:true});
$("a[rel='imagebox-even']").colorbox({slideshow:true});
$("a[rel='imagebox-amina']").colorbox({slideshow:true});
$("a[rel='imagebox-cumulus']").colorbox({slideshow:true});
$("a[rel='imagebox-wee']").colorbox({slideshow:true});
$("a[rel='imagebox-four']").colorbox({slideshow:true});
$("a[rel='imagebox-teen']").colorbox({slideshow:true});
+3
source share
5 answers

Assuming there are no other values imagebox-*you want to exclude:

$("a[rel^='imagebox-']").colorbox({slideshow:true});

Speaking of which, it is best to avoid attribute selection, and as a rule, it is best for you not to restructure your problem in order to provide a better solution. How could you use classes:

<a href="..." class="imagebox teen"> ...

Note the space: two classes are assigned. So you can do:

$("a.imagebox")...

for all of them. Or:

$("a.imagebox.teen")...

only for one of them.

Remember that you can add multiple selectors with a comma:

$("a.class1, a.class2")...

, , 1 OR class2 :

$("a.class1.class2")...

, , , 1 2.

+12

attributeStartsWith , .

$("a[rel^='imagebox-']").colorbox({slideshow:true});
+3

Could you use

$("a[rel^='imagebox']").colorbox({slideshow:true});

which applies to any tag with the rel attribute that starts with the image window?

+1
source

Remember that it is structured as a minimum.

$("a[rel='imagebox-all']")
.colorbox({
slideshow: !0
}), $("a[rel='imagebox-new']")
.colorbox({
slideshow: !0
}), $("a[rel='imagebox-even']")
.colorbox({
slideshow: !0
}), $("a[rel='imagebox-amina']")
.colorbox({
slideshow: !0
}), $("a[rel='imagebox-cumulus']")
.colorbox({
slideshow: !0
}), $("a[rel='imagebox-wee']")
.colorbox({
slideshow: !0
}), $("a[rel='imagebox-four']")
.colorbox({
slideshow: !0
}), $("a[rel='imagebox-teen']")
.colorbox({
slideshow: !0
})
+1
source

Try the following:

var selectors = [
    "a[rel='imagebox-all']",
    "a[rel='imagebox-new']",
    "a[rel='imagebox-even']",
    // ...
];

$.each(selectors, function(){
    $(this).colorbox({slideshow:true});
});

Then, when you need to add a new selector, just add it to the array of selectors.

0
source

Source: https://habr.com/ru/post/1724590/


All Articles