Is there a shorter way to write this script? (Targeting multiple elements to run the same function)
So I have this nice slider script that I want to use on this page: http://tuscaroratackle.com/rods for several instances on the page. (In other words each rod posting will have it's own slider, a total of about 11 sliders on the page)
In order to run the script I have to include this function declaration:
$(document).ready(function(){
$("#rod-slider1").easySlider();
$("#rod-slider2").easySlider();
$("#rod-slider3").easySlider();
$("#rod-slider4").easySlider();
$("#rod-slider5").easySlider();
$("#rod-slider6").easySlider();
$("#rod-slider7").easySlider();
$("#rod-slider8").easySlider();
...etc...
});
So the question开发者_JAVA技巧 here (is a jQ noob question I know) is can I combine those lines into one by adding all the ID selectors into the first function? And if so, what would be the proper format for writing it that way?
You can also use a class:
$(document).ready(function(){
$(".rod-slider").easySlider();
});
The slider will now be applied to all/any elements having the class rod-slider
.
If you want/need to use ids, you can do so by separating them with a comma:
$(document).ready(function(){
$("#rod-slider1, #rod-slider2, #rod-slider3, #etc").easySlider();
});
Or you can use the add
method.
If you don't want to modify you current html, you can use the starts with
selector:
$(document).ready(function(){
$("[id^='rod-slider']").easySlider();
});
You can use the starts-with
selector
$(document).ready(function(){
$("[id^='rod-slider']").easySlider();
});
This translates to select all elements that have an id attribute that starts with rod-slider
You can improve the performance of this if you know the tag name is the same for all elements. For example if they are all divs you could write it as
$("div[id^='rod-slider']").easySlider();
for better performance..
$(".rodslider").easySlider();
Where "rodslider" is a class and not an id selector.
Give them all a common class, then use a .class
selector, like this:
$(function(){
$(".rod-slider").easySlider();
});
You can add a class and select them all together. For example if they are DIVs you can just do this way
<div class="rodslider"></div>
and
$(document).ready(function(){
$("div.rodslider").easySlider();
});
You could do:
$(document).ready(function(){
for (var i = 1; i <= 8; i++) {
$("#rod-slider" + i).easySlider();
}
});
or just use the class selector...
$(document).ready(function(){
$(".rod-slider").easySlider();
});
精彩评论