简体   繁体   English

如何将 CSS 样式添加到使用 JavaScript 创建的 HTML 元素?

[英]How to add CSS style to HTML elements created with JavaScript?

I have created HTML elements with JavaScript to pull data from the back-end server.我创建了 HTML 元素和 JavaScript 从后端服务器提取数据。 I am trying to add CSS style to the elements, but I am having trouble as to how.我正在尝试将 CSS 样式添加到元素中,但我不知道如何。

I have tried using getElementById and setAttribute, but I'm keep getting an error.我曾尝试使用 getElementById 和 setAttribute,但我不断收到错误消息。 Whenever each item is pulled out from the back-end server, I want each information to be wrapped with a solid black border.每当从后端服务器拉出每个项目时,我都希望每个信息都用纯黑色边框包裹。

This is the code:这是代码:

let div = "<div>";
        
        for (let i = 0; i < Items.length; i++) {

            div += "<h3>" + Items[i].title + "</h3><p><i><b> Posted: " + Items[i].time + "</b></i></p><p>" + Items[i].body + "</p>"

        }

        div += "</div>";

        $("#news-articles").html(div);

You can add class or style attributes while creating the HTML string like:您可以在创建 HTML 字符串时添加classstyle属性,例如:

"<div class=\"red\" style=\"background: blue\">".

I recommend using single quotes or template literal so you wouldn't have to escape the nested double quotes:我建议使用单引号或模板文字,这样您就不必转义嵌套的双引号:

'<div class="red" style="background: blue">'

 const Items = [{ title: 'hi', time: 2, body: 'hello' }] let div = "<div class=\"red\" style=\"background: blue\">"; for (let i = 0; i < Items.length; i++) { div += "<h3>" + Items[i].title + "</h3><p><i><b> Posted: " + Items[i].time + "</b></i></p><p>" + Items[i].body + "</p>" } div += "</div>"; $("#news-articles").html(div);
 .red { color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="news-articles"></div>

You complicate the code a lot.您使代码复杂化了很多。 Just use list tags只需使用列表标签

    <ul>
    for (let i = 0; i < Items.length; i++) {
   <li>Coffee</li>....}
   ul li {
  background: #cce5ff;
  margin: 5px;
}

Where is your CSS?你的 CSS 在哪里?

Just load a CSS file with styles for every element inside the #news-articles container:只需为#news-articles 容器中的每个元素加载一个 CSS 文件和 styles :

#news-articles h3 {
/* rules */
}

#news-articles p {
/* rules */
}

etc...

I suggest you to wrap every news in a div for easily achieving what you pretend, which is adding a border to each of them.我建议您将每个新闻都包装在一个 div 中,以便轻松实现您所伪装的内容,即为每个新闻添加边框。

for (let i = 0; i < Items.length; i++) {

            div += "<div class='container'><h3>" + Items[i].title + "</h3><p><i><b> Posted: " + Items[i].time + "</b></i></p><p>" + Items[i].body + "</p></div>"

        }

And then...接着...

#news-articles .container {
    border: 1px solid #000;
}

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

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