简体   繁体   中英

how to add a line break on javascript variable

really simple question and cant figure it out. I am trying to add a line break here on my table header

var text = "<table id='test' class='test'>";
    text += "<tr><th> style='font-size:16px'>Cool \nStuff</th></tr>";

I have tried to add a line break using <br> and \\n and no luck, can anyone help me

\\n puts a newline in the string, but HTML treats newlines as spaces. To put in a line break, you:

  1. Use a <br> ("break") element:

     var text = "<table id='test' class='test'>"; text += "<tr><th style='font-size:16px'>Cool<br>Stuff</th></tr>"; 

    or,

  2. Put the first line in one block element, the second in another:

     var text = "<table id='test' class='test'>"; text += "<tr><th style='font-size:16px'>" + "<div>Cool</div>" + "<div>Stuff</div>" + "</th></tr>"; 

That sort of thing.

Use <br> should work fine. Note you had a typo with the opening th

 var text = "<table id='test' class='test'>"; text += "<thead>"; text += "<tr><th style='font-size:16px'>Cool <br/>Stuff</th></tr>"; text += "</thead>"; text += "</table>"; document.getElementById("z").innerHTML = text; 
 <div id="z"></div> 

Adding </br> should work, see the code snippet below. Please note that there is an error in your HTML. <th> style='font-size:16px'> contains two closing > tags, you should remove the first one.

 var text = "<table id='test' class='test'>"; text += "<tr><th style='font-size:16px'> Cool </br> Stuff</th></tr>"; document.write(text) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Separate each line in the header into <span>Cool</span><span>Stuff</span> and add the following styles to the span:

span {
    width: 100%;
    display: block;
}

Example:

 // using your javascript example... var text = "<table id='test' class='test'>"; text += "<tr><th> style='font-size:16px'><span style='width:100%; display:block;'>Cool</span><span style='width:100%; display:block;>Stuff</span></th></tr>"; 
 .table { width: 100%; display: block; } .table > thead > tr > th { padding: 15px; text-align: center; border: solid 2px #d2d2d2; background-color: #000000; color: #ffffff; } .table > thead > tr > th > span { width: 100%; display: block; } 
 <table class="table"><!-- START TABLE --> <thead> <tr> <th><span>Cool</span><span>Stuff</span></th> <th>Column 2</th> <th>Column 3</th> <th>Column 4</th> </tr> </thead> <tbody class="tbody"> </tbody> </table><!-- /END TABLE --> 

Using <br> works perfectly.

(function () {
    text += '<th>Cool<br>Stuff</th>';
})();

Relevant JSFiddle

http://jsfiddle.net/68Lc0d7t/1/

You missed the closing tag in the <th> tag.. Above is a simple working fiddle with <br> tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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