问题
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:
- I need to do it via a variable because the contents of the variable changes often.
- 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