如何将样式表应用于动态创建的元素? [英] How to apply style sheets to dynamically created elements?

查看:27
本文介绍了如何将样式表应用于动态创建的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

this should be an easy one: I have the following code:

<!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>

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

The problem is: The style specified in the bootstrap.min for the class "table" is never applied upon loading the side. Do I have to do something additionally? I test it in the most recent version of Safari.

有什么帮助吗?

干杯特卫普

推荐答案

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

It is not dynamically created issue. It is because you haven't set the class to table. As Bootstrap Docs says:

您必须使用 才能使类工作.

You have to use <thead> and <tbody> for the class to work.

添加您的答案:

var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);

添加此以快速修复:

$("tr:first-child").wrap("<thead/>");

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

Your final code should look like:

    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);

这篇关于如何将样式表应用于动态创建的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆