I have the following jquery which I want to simplify.
I am just repeating the same things.
Could anyone give me suggestions please.
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:tr开发者_JS百科ue});
$("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});
Assuming there are no other values of imagebox-*
you want to exclude:
$("a[rel^='imagebox-']").colorbox({slideshow:true});
That being said, attribute selectors are usually best avoided and you're typically better off restructuring your problem to allow a better solution. Like you could use classes:
<a href="..." class="imagebox teen"> ...
Note the space: that's two classes assigned. So you can do:
$("a.imagebox")...
for all of them. Or:
$("a.imagebox.teen")...
for just one of them.
Remember as well you can add multiple selectors with a comma:
$("a.class1, a.class2")...
will apply what you're doing to anchors with class1 OR class2 versus:
$("a.class1.class2")...
which applies whatever you're doing to anchors that have class1 AND class2.
You can user the attributeStartsWith selector which matches elements that have the specified attribute and it starts with a certain value.
$("a[rel^='imagebox-']").colorbox({slideshow:true});
Could you use
$("a[rel^='imagebox']").colorbox({slideshow:true});
which applies to any a tag with a rel attribute that starts with imagebox?
Remember to have it structured at least, like this.
$("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
})
Try this:
var selectors = [
"a[rel='imagebox-all']",
"a[rel='imagebox-new']",
"a[rel='imagebox-even']",
// ...
];
$.each(selectors, function(){
$(this).colorbox({slideshow:true});
});
Then, whenever you need to add a new selector, just add it to the selectors array.
精彩评论