开发者

jQuery - call function based on page 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜