If body class equals X then do something?
I have this code running from an external script for an image slider for every page on a site.
$(document).ready(function() {
$("#slideshow").show();
$('#slider1').anythingSlider({
buildNavigation: false,
delay: 8000
})
On one of the pages I don't want the image slider to rotate automatically so I need to add an extra variable. I've put a class on the body of the page and want to do something along the lines of...
If the body has a class of 'partnerCharitiesDetail' then run this script instead of the generic one
This is what I have tried below (without success). I have 2 questions really,
1) What happens in jQuery when there are 2 identical scripts running (like this example), will it overwrite the older one with the开发者_开发知识库 newer one?
2) Where am I going wrong?! Is my approach the best way to do it?
$(document).ready(function() {
$("#slideshow").show();
$('#slider1').anythingSlider({
buildNavigation: false,
delay: 8000
})
if ($('body.partnerCharitiesDetail').length > 0){
$('#slider1').anythingSlider({
buildNavigation: false,
delay: 8000,
startStopped: false
})
}
Thanks!
Use the hasClass()
method to check if an element has a certain class.
Also, your code is a little repetitive (and could even cause AnythingSlider to run twice) — I would write it like this instead:
$(document).ready(function() {
// Initialize options first
var options = {
buildNavigation: false,
delay: 8000
};
// Only disable startStopped if the body has this class
if ($('body').hasClass('partnerCharitiesDetail')) {
options.startStopped = false;
}
// Show the #slideshow element and start the slideshow
$('#slideshow').show();
$('#slider1').anythingSlider(options);
});
have you looked at hasClass
So you could say
if($("body").hasClass("partnerCharitiesDetail"))
{
}
else
{
}
if ($('body').hasClass('partnerCharitiesDetail')) {
...
I would suggest:
$("#slideshow").show();
var options = {
buildNavigation: false,
delay: 8000
};
if ($('body').hasClass('partnerCharitiesDetail')) {
options.startStopped = false;
}
$('#slider1').anythingSlider(options);
The behavior depends on how the anythingSlider plugin you're using works. If the plugin accounts for reinitializing a certain element then the second initialization would override the previous, but more likely than not you'd just really mess up your DOM and get double the event listeners etc.
As pointed out, the proper way for checking if something has a class is .hasClass("classname").
if($("body").hasClass("partnerCharitiesDetail")) {
}
else {
}
Although in this specific case I'd just do
$('#slider1').anythingSlider({
buildNavigation: false,
delay: 8000,
startStopped: !($("body").hasClass("partnerCharitiesDetail"))
})
and maybe add a comment for future explorers.
Try this
if($("body").isClass(".partnerCharitiesDetail")) { //code if body has specific class name } else { //code if body has no specific class name }
精彩评论