How can I add a CSS class to a page <head> with jquery?

回眸只為那壹抹淺笑 提交于 2019-12-13 05:58:19

问题


I want to use jquery to append a new CSS class to the head script of a document to change an element on that page.

It should be simple by using something like this:

var myhex = #e6399b;
$("<style type='text/css'> #someid { color:myhex; } </style>").appendTo("head");

I've created a FIDDLE to test with, but I can't get it to work. I think it's something really simple with the syntax of having a JS variable in the middle of HTML code - I tried '+myhex+' and +myhex+ but to be honest I was guessing at this point.

Notes:

  1. I need to do it via a variable because the contents of the variable changes often.
  2. I realise the immediate answer is "use .css()" but in this scenario I can't use it because I'm adding a style to an element inside a jquery dialog. The only way of doing so is via jquery's dialogClass command (i.e. you have to set up the style via a 'class', rather than via .css().

Thanks for any help you can give.


回答1:


You need to quote strings, and add variables to strings with concentanation (+ sign) :

var myhex = '#e6399b';
$("<style type='text/css'> #someid { color:"+myhex+"; } </style>").appendTo("head");

FIDDLE



来源:https://stackoverflow.com/questions/12219188/how-can-i-add-a-css-class-to-a-page-head-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!