开发者

jQuery - call function based on page id

开发者 https://www.devze.com 2023-01-18 10:02 出处:网络
how can I check the id on every page\'s <body> tag and perform a set of unique jQuery functi开发者_JAVA技巧ons based on the page\'s id?

how can I check the id on every page's <body> tag and perform a set of unique jQuery functi开发者_JAVA技巧ons based on the page's id?

for example, I have a page with id=red and another page with id=blue. On page load, I need to check the id and then assign the appropriate color to a div on the page.

thanks


by using .is(),

$(function(){
   if ($('body').is('#red')) {
        $('.someElement').addClass('red')
   }
})

by using the length property,

$(function(){
   if ($('body#red').length) {
        $('.someElement').addClass('red')
   }
});

by using .attr(),

$(function(){
   if ($('body').attr('id') == 'red') {
        $('.someElement').addClass('red')
   }
});


$(document).ready(function(){
   var id = $('body').attr('id');
});

The above code will get your the id of the body tag and then you can simply select the div and change it's background colour with $('#IDofDIV').css('background',id), assuming your id value is always an acceptable css colour.

Hope that helps!


var bodyId = $('body').attr('id');

switch(bodyId)
{
case 'red':
  ...
  break;
case 'blue':
  ...
  break;
default:
  ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消