如何将样式表应用于动态创建的元素?

Kai*_*Kai 2 javascript css twitter-bootstrap

这应该很简单:我有以下代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
 <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
        var table = document.createElement("table");
        table.setAttribute("id","table");
        var headRow = document.createElement("tr");
        var dataRow = document.createElement("tr");
        var head = document.createElement("th");
        var data = document.createElement("td");
        head.innerHTML="head";
        data.innerHTML="data";
        headRow.appendChild(head);
        dataRow.appendChild(data);
        table.appendChild(headRow);
        table.appendChild(dataRow);
        console.log(document.styleSheets);
        table.className = "table";
        document.getElementById("test").appendChild(table);
    });
  </script>
</head>
<body>
<div id="test"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

问题是:在加载边时,从不应用bootstrap.min中为类"table"指定的样式.我还需要做些什么吗?我在最新版本的Safari中测试它.

任何帮助?

干杯Twerp

Pra*_*man 5

它不是动态创建的问题.这是因为您没有将类设置为table.正如Bootstrap Docs所说:

你必须使用<thead><tbody>让班级工作.

要添加你的答案:

var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
Run Code Online (Sandbox Code Playgroud)

添加此项以进行快速修复:

$("tr:first-child").wrap("<thead/>");
Run Code Online (Sandbox Code Playgroud)

您的最终代码应如下所示:

    var table = document.createElement("table");
    table.setAttribute("id","table");
    var headRow = document.createElement("tr");
    var dataRow = document.createElement("tr");
    var head = document.createElement("th");
    var data = document.createElement("td");
    var thead = document.createElement("thead");
    thead.appendChild(headRow);
    var tbody = document.createElement("tbody");
    tbody.appendChild(dataRow);
    head.innerHTML="head";
    data.innerHTML="data";
    headRow.appendChild(head);
    dataRow.appendChild(data);
    table.appendChild(thead);
    table.appendChild(tbody);
    console.log(document.styleSheets);
    table.className = "table";
    document.getElementById("test").appendChild(table);
Run Code Online (Sandbox Code Playgroud)