简体   繁体   中英

Adding stylesheets to head dynamically with jQuery and php

I am looking for to adding specific style-sheets to the <head></head> section of the current page. I can use jQuery, and the following jQuery snippet works. Problem is a php code calls those style-sheets and I need to integrate my php code into the jQuery, which I can't figure out how to do it.

Here is the php code:

<?php
    $this->style()
            ->appendStylesheet($this->APP_STATIC_URL . '/templates/' . $this->APP_TEMPLATE . '/skins/' . $this->APP_SKIN . '/content_blog_view_{4}.css', 'screen')
            ->appendStylesheet($this->APP_STATIC_URL . '/templates/' . $this->APP_TEMPLATE . '/skins/' . $this->APP_SKIN . '/content_blog_view_{3}.css', 'screen')
            ->appendStylesheet($this->APP_STATIC_URL . '/templates/' . $this->APP_TEMPLATE . '/skins/' . $this->APP_SKIN . '/content_blog_view_{2}.css', 'screen')
            ->appendStylesheet($this->APP_STATIC_URL . '/templates/' . $this->APP_TEMPLATE . '/skins/' . $this->APP_SKIN . '/content_blog_view_{1}.css', 'screen');
    echo $this->style()->minify();
?>

It generates the following html code:

<link href="http://redspark/templates/default/skins/default/content_blog_view_{4}.css" media="screen" rel="stylesheet" type="text/css" >
<link href="http://redspark/templates/default/skins/default/content_blog_view_{3}.css" media="screen" rel="stylesheet" type="text/css" >
<link href="http://redspark/templates/default/skins/default/content_blog_view_{2}.css" media="screen" rel="stylesheet" type="text/css" >
<link href="http://redspark/templates/default/skins/default/content_blog_view_{1}.css" media="screen" rel="stylesheet" type="text/css" >

I need to add the above mentioned php code in the following jQuery code (or any other better solution you know).

<script>
var $head = $("head");
var $headlinklast = $head.find("link[rel='stylesheet']:last");
var linkElement = "<link rel='stylesheet' href='/css/masterBlaster.css' type='text/css' media='screen'>";
if ($headlinklast.length){
   $headlinklast.after(linkElement);
}
else {
   $head.append(linkElement);
}
</script> 

You can echo your PHP code in a Javascript variable and then use it.

Something like this:

var styles = "<?= echo $this->style()->minify(); ?>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM