如何将CSS类添加到页面< head>与jQuery的? [英] How can I add a CSS class to a page <head> with jquery?

查看:79
本文介绍了如何将CSS类添加到页面< head>与jQuery的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jquery将新的CSS类附加到文档的头脚本中,以更改该页面上的元素.

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");

我已经创建了一个 FIDDLE 进行测试,但无法使其正常工作.我认为在HTML代码中间使用JS变量的语法确实非常简单-我尝试了'+myhex+'+myhex+,但老实说我在这一点上是在猜测.

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.

注释:

  1. 我需要通过变量来执行此操作,因为变量的内容经常更改.
  2. 我意识到直接的答案是使用.css()",但是在这种情况下我无法使用它,因为我正在向jquery对话框中的元素添加样式.唯一的方法是通过jquery的dialogClass命令(即,您必须通过类"而不是通过.css()来设置样式.
  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.

推荐答案

您需要用引号引起来,并将变量添加到包含(+)的字符串中:

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

这篇关于如何将CSS类添加到页面&lt; head&gt;与jQuery的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆