1

我有一行我添加了一些 css:

$("#foo").html("Some text with a link <a href=\"link.html\">Link here</a>").css({
     'margin': '10px 0px',
     'padding': '15px 10px 15px 50px',
     'clear': 'left'
});

我想将链接更改为黑色,因此添加此 css 应该可以:

a.link {
     color: black
}

我想最好的办法是指向一个 css 文件,而不是添加a.link. 但想知道这是否可能。显然这样的事情不起作用,因为它不是正确的 json 格式:

$("#foo").html("Some text with a link <a href=\"link.html\">Link here</a>").css({
     'margin': '10px 0px',
     'padding': '15px 10px 15px 50px',
     'clear': 'left',
     'a:link: color': 'black'
 });

有没有办法做到这一点?

4

2 回答 2

7

您不能从父元素 css 函数更新子元素的样式。相反,为什么不将它添加到 css 文件中,

#foo a.link { color: black; }

如果您对如何通过脚本添加它感到好奇..

$("#foo")            //Added class link to the link tag--v
   .html('Some text with a link <a href=\"link.html\" class="link">Link here</a>')
   .css({'margin': '10px 0px', 'padding': '15px 10px 15px 50px', 'clear': 'left'})
   .find('a.link').css({'color': 'black'}); 
   //^-- this would find the link tag and updates its css
于 2012-11-06T22:49:33.333 回答
0

为什么不插入带有所需样式的样式标签?<style type="text/css">a.link: {color: black}</style>或内联定义链接颜色

$("#foo").html('Some text with a link <a style="color: black" href="link.html">Link here</a>').css({'margin': '10px 0px', 'padding': '15px 10px 15px 50px', 'clear': 'left'});

.css用于定义内联 css 样式,而不是由选择器定义的样式,例如a.link,为此使用<style>标签。

于 2012-11-06T22:47:56.083 回答