javascript 如何在动态生成的元素上应用样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18526678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to apply style on dynamically generated element
提问by Nav Kumar
function createList(arrunique, arrayout) {
for (i = 0; i < arrayout[0].length; i++) {
var divIdC = i;
var divIdT = i + 10;
$('#tb').append('<select name="combo" style="float:left; width:100px;" id="' + divIdC + '" onchange="getComboVal(this,' + divIdC + ')"></select>');
$('#tb').append('<input type="text" name = "textBox" style= "width:100px;" id="' + divIdT + '" onkeyup="validate(this,"' + divIdT + '") value="0">');
var select = document.getElementById(divIdC);
select.options[select.options.length] = new Option("Select " + arrunique[i][0]);
for (j = 1; j < arrunique[i].length; j++) {
select.options[select.options.length] = new Option(arrunique[i][j]);
};
};
}
In this code I want to generate a combo box and a textbox and I want to apply some style sheet attribute or any class. How can I do this. Its not working.
在这段代码中,我想生成一个组合框和一个文本框,我想应用一些样式表属性或任何类。我怎样才能做到这一点。它不工作。
回答by m59
There are many, many ways of styling a javascript created element. Here are a few. Click here for live demo.
有很多很多方法可以为 javascript 创建的元素设置样式。这里有一些。 单击此处查看现场演示。
var myElem = document.createElement('div');
myElem.style.color = '#FFF';
with jQuery:
使用 jQuery:
var $myElem = $('<div></div>');
$myElem.css('color', '#FFF');
or jQuery css object syntax (for passing multiple styles)
或 jQuery css 对象语法(用于传递多种样式)
$myElem.css({display: 'block', background: '#000'});
Rather than adding the style after creating the element, you may also consider just adding a class to the element after creating it and styling this class in your css file.
与其在创建元素后添加样式,您还可以考虑在创建元素并在 css 文件中设置该类的样式后向该元素添加一个类。
CSS file:
CSS文件:
.myElem {
color: #FFF;
}
myElem.className = 'myElem';
or
或者
$myElem.addClass('myElem');
回答by HymanTurky
$('#tb').append('<input type="text" class="YOURCLASS" name = "textBox" style= "width:100px;" id="'+divIdT+'" onkeyup="validate(this,"'+divIdT+'") value="0">');