Подтвердить что ты не робот

Как вставить большой блок HTML в JavaScript?

Если у меня есть блок HTML со многими тегами, как вставить его в JavaScript?

var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = 'HERE TOO MUCH HTML that is much more than one line of code';
document.getElementById('posts').appendChild(div);

Как мне это сделать правильно?

4b9b3361

Ответ 1

Вы можете сохранить HTML-блок в невидимом контейнере (например, <script>) в своем HTML-коде, а затем использовать его innerHTML во время выполнения в JS

Например:

var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;
document.getElementById('targetElement').appendChild(div);
.red {
    color: red
}
<script id="blockOfStuff" type="text/html">
    Here some random text.
    <h1>Including HTML markup</h1>
    And quotes too, or as one man said, "These are quotes, but
    'these' are quotes too."
</script>

<div id="targetElement" class="red"></div>

Ответ 2

Template literals могут решить вашу проблему, поскольку это позволит писать многострочные строки и функции интерполяции строк. Вы можете использовать переменные или выражение внутри строки (как указано ниже). Легко вставлять объемный html в удобной для читателя форме.

Я изменил приведенный пример и посмотрю его ниже. Я не уверен, сколько буклетов Template literals совместимых с браузером. Пожалуйста, прочтите здесь литералы о шаблонах.

var a = 1, b = 2;
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = '
    <div class="parent">
        <div class="child">${a}</div>
        <div class="child">+</div>
        <div class="child">${b}</div>
        <div class="child">=</div>
        <div class="child">${a + b}</div>
    </div>
';
document.getElementById('posts').appendChild(div);
.parent {
  background-color: blue;
  display: flex;
  justify-content: center;
}
.post div {
  color: white;
  font-size: 2.5em;
  padding: 20px;
}
<div id="posts"></div>

Ответ 3

Несмотря на неточный характер вопроса, здесь мой интерпретирующий ответ.

var html = [
    '<div> A line</div>',
    '<div> Add more lines</div>',
    '<div> To the array as you need.</div>'
].join('');

var div = document.createElement('div');
    div.setAttribute('class', 'post block bc2');
    div.innerHTML = html;
    document.getElementById('posts').appendChild(div);

Ответ 4

Если я правильно понимаю, вы ищете многострочное представление для удобочитаемости? Вы хотите что-то вроде строки здесь на других языках. Javascript может приблизиться к этому:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

Ответ 5

Добавьте каждую строку кода в переменную, а затем напишите переменную во внутренний HTML. См. Ниже:

var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
var str = "First Line";
str += "Second Line";
str += "So on, all of your lines";
div.innerHTML = str;
document.getElementById('posts').appendChild(div);

Ответ 6

Если вы используете тот же домен, вы можете создать отдельный HTML файл, а затем импортировать его с помощью кода из этого ответа @Stano:

fooobar.com/questions/51675/...

Ответ 7

function searchKeyPress(e)
{
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('btnUnblock').click();
        return false;
    }
    return true;
}
function createLink() {
var theId = document.getElementById('getId').value;
var YouTube = "youtube";
var YouTube2 = "https://youtu.be/";
var YouTube3 = "http://youtu.be/";
var YouTube4 = "youtu.be/";
if (theId.indexOf(YouTube) >= 0) {
var string = theId.split('=');
theId = string[1];
}
if (theId.indexOf(YouTube2) >= 0) {
var sString = theId.split('/');
theId = sString[3];
}
if (theId.indexOf(YouTube3) >= 0) {
var ssString = theId.split('/');
theId = ssString[3];
}
if (theId.indexOf(YouTube4) >= 0) {
var sssString = theId.split('/');
theId = sssString[3];
}
theId = theId.replace("&feature", '');
var newId = theId.match(/.{1,11}/g);
var customLink = 'http://www.youtube-nocookie.com/embed/' + newId[0] + '';
document.getElementById("player").src = "" + customLink;
document.getElementById("directLink").href = "" + customLink;
}
function buttonOne() {
document.getElementById("player").height = "480";
document.getElementById("player").width = "720";
}
function buttonTwo() {
document.getElementById("player").height = "720";
document.getElementById("player").width = "1280";
}
function buttonThree() {
document.getElementById("player").height = "1080";
document.getElementById("player").width = "1920";
}
<h1>Unblocker</h1>
<p>(If says video is blocked by VEVO, just visit the VEVO site
and watch it there at <a href=http://www.vevo.com> Vevo</a>.)
<strike><p>Type in your ID or paste one of these examples:<br /> x35P2wTX0zg<br />
fuDIevJyqbI
</p></strike>
  <input onkeypress="return searchKeyPress(event);" name="getId" type="text" id="getId" />
<button id="btnUnblock" onclick="createLink()">Unblock</button>
<p>Select player size:</p>
<p><button onclick="buttonOne()">720x480</button></p>    
<p><button onclick="buttonTwo()">1280x720</button></p>
<p><button onclick="buttonThree()">1920x1080</button></p>
<p>
<iframe id="player" height=480 width=720 src="" allowfullscreen></iframe>
</p>
<a id="directLink" href="">Direct link</a>

Ответ 8

Самый простой способ вставить html-блоки - это использовать строки шаблона (обратные ссылки). Это также позволит вам вставлять динамический контент через $ {...}:

document.getElementById("log-menu").innerHTML = '
            <a href="#"> 
               ${data.user.email}
            </a>
            <div class="dropdown-menu p-3 dropdown-menu-right">
                <div class="form-group">
                    <label for="email1">Logged in as:</label>
                    <p>${data.user.email}</p>
                </div>
                <button onClick="getLogout()" ">Sign out</button>
            </div>
    '