简体   繁体   English

如何在动态生成的元素上应用样式

[英]how to apply style on dynamically generated element

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. 它不起作用。

There are many, many ways of styling a javascript created element. 样式化javascript创建的元素的方式有很多。 Here are a few. 这里有一些。 Click here for live demo. 单击此处进行实时演示。

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');
$('#tb').append('<input type="text" class="YOURCLASS" name = "textBox" style= "width:100px;" id="'+divIdT+'" onkeyup="validate(this,"'+divIdT+'") value="0">');

See this simplified jsFiddle . 请参阅此简化的jsFiddle Ensure that the console is not generating an errors, and that you're calling the createList() function. 确保控制台没有生成错误,并且您正在调用createList()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM