[英]How can I apply css to elements created with append()
I am trying to change the text colour of certain options in a but it is not working. 我正在尝试更改中某些选项的文本颜色,但是它不起作用。 none are red
没有红色
var style="color:red"
$('#newuserSelect')
.append($('<option>', {
value: "0",
title: "hello",
style: style
})
.text("my text"));
http://jsfiddle.net/ZDYEd/ the colour is black when it should be red http://jsfiddle.net/ZDYEd/应为红色时为黑色
The property name to use is "css", not "style". 要使用的属性名称是“ css”,而不是“ style”。 Also the value should be an object whose properties are the CSS properties to set.
值也应该是一个对象,其属性是要设置的CSS属性。
$('#newuserSelect')
.append($('<option>', {
value: "0",
title: "hello",
css: { color: "red" }
})
.text("my text"));
You can, incidentally set the text with that initialization object too: 您也可以使用该初始化对象来设置文本:
$('#newuserSelect')
.append($('<option>', {
value: "0",
title: "hello",
css: { color: "red" },
text: "my text"
})
);
Now, this does work , but it's important to note that when you're looking at the page with the <select>
element not "open", you're not looking at the <option>
elements. 现在, 这确实可行 ,但是需要注意的是,当您在查看
<select>
元素未“打开”的页面时,您并未在查看<option>
元素。 If you want the selected text to be red, then you need to also style the <select>
element itself. 如果希望所选文本为红色,则还需要设置
<select>
元素本身的样式。 When there's only one <option>
, the <select>
cannot be "opened" so you never see the style of the <option>
. 当只有一个
<option>
,不能“打开” <select>
因此您永远看不到<option>
的样式。
I can't recall exactly but it may be the case that IE, or old versions of it anyway, won't pay attention to styles on <option>
elements. 我记不清了,但是IE或它的旧版本可能不会注意
<option>
元素上的样式。 IE <select>
was implemented in a really weird way in old versions. IE
<select>
在旧版本中以一种非常奇怪的方式实现。
Actually, $(xyz).append(abc)
will return the object of xyz
not abc
. 实际上,
$(xyz).append(abc)
将返回xyz
的对象,而不是abc
。 And by the way, The proper way to set the css for an element is to use .css() function. 顺便说一下,设置元素的CSS的正确方法是使用.css()函数。 Please read here for full reference.
请阅读此处以获取完整参考。
So I would suggest you to use .appendTo in your current context. 因此,我建议您在当前上下文中使用.appendTo。 That will fit your need.
那将适合您的需求。 Unlike .append() , .appendTo() will return the object of xyz [
$(xyz).appendTo(abc)
] 与.append()不同, .appendTo()将返回xyz [
$(xyz).appendTo(abc)
]的对象
Try this, 尝试这个,
$('<option>', { value: "0", title: "hello" })
.appendTo('#newuserSelect')
.text('my text')
.css({color:'red'});
Why calling jQuery to create this tiny piece of HTML? 为什么要调用jQuery创建这一小段HTML?
$('#newuserSelect').append(
'<option value="0" title="hello" style="color:red">my text</option>'
);
Your JavaScript is fine. 您的JavaScript很好。 You can't color individual options with CSS.
您不能使用CSS为单个选项着色。 This is the output of your original fiddle!
这是您原始提琴的输出!
Edited: CSS Text color not taking effect in Chrome 31 for OSX Mavericks 编辑:CSS文本颜色在OS X Mavericks的Chrome 31中不生效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.