简体   繁体   English

使用Vanilla JS向表中动态添加内容

[英]Dynamically adding content to table using Vanilla JS

I'm trying to add as many rows as users I have in my database to a table. 我试图将数据库中用户的行数添加到表中。 I'm getting the users' info from the backend via ajax request, then when the response (JSON) arrive my code pass it to I silly template I'd created using underscore.js . 我通过ajax请求从后端获取用户的信息,然后当响应(JSON)到达时,我的代码将其传递给我使用underscore.js创建的愚蠢模板。

After underscore rendered the template this is what i got: 下划线呈现模板后,这就是我得到的:

<tr data-id="29">
    <td>email@themail.ma</td>

    <td>
        <ul style="display:inline-block; padding-left:0; margin-bottom:0">
            <li style="display:inline-block;"><a href="#"></a></li>
        </ul>
    </td>

    <td>Activo</td>

    <td>No caduca</td>

    <td>
        <span data-placement="left" data-toggle="tooltip" title="Eliminar usuario">
            <a class="icon-trash" href="#" role="button"
               data-toggle="modal"
               data-target="#js-confirm-modal"
               data-action="js-del-user"
               data-msg="Desea eliminar el usuario?"></a>
        </span>

        <span data-placement="left" data-toggle="tooltip" title="Cambiar contraseña">
            <a class="icon-key" href="#" role="button"
               data-toggle="modal"
               data-target="#js-confirm-modal"
               data-action="js-chg-pass"
               data-msg="Cambiar contraseña del usuario?"></a>
        </span>

        <span data-placement="left" data-toggle="tooltip" title="Bloquear usuario">
            <a class="icon-lock" href="#" role="button"
               data-toggle="modal"
               data-target="#js-confirm-modal"
               data-action="js-block-user"
               data-msg="Desea bloquear el usuario?"></a>
        </span>

        <span data-placement="left" data-toggle="tooltip" title="Desbloquear usuario">
            <a class="icon-lock-open" href="#" role="button"
               data-toggle="modal"
               data-target="#js-confirm-modal"
               data-action="js-unblock-user"
               data-msg="Desea desbloquear el usuario?"></a>
        </span>

    </td>
</tr>

So far so good, but when I do something like this: 到目前为止一切顺利,但是当我做这样的事情时:

tbody.innerHTML = html;

// or 

let parseHTML = function(str) {
  var tmp = document.implementation.createHTMLDocument();
  tmp.body.innerHTML = str;
  return tmp.body.children;
};

parseHTML(html);  // and then adding the returned codes to my tbody

It just looses the html table format (td, tr tags, etc) 它只是失去了html表格式(td,tr标签等)

I often use template literals for this, constructing a long string of HTML using the += operator and then using document.innerHTML to append the final HTML string to my page. 我经常为此使用模板文字,使用+=运算符构造一个较长的HTML字符串,然后使用document.innerHTML将最终的HTML字符串附加到我的页面上。

A simple example might look like this: 一个简单的示例可能如下所示:

 const helloWorlds = { spanish: '¡Hola Mundo!', polish: 'Witaj świecie!', french: 'Bonjour le monde!' } const helloWorldsKeys = Object.keys(helloWorlds); let listMarkup = ''; for (let i = 0; i < helloWorldsKeys.length; i++) { listMarkup += '<li class="listItem">' + helloWorlds[helloWorldsKeys[i]] + '</li>'; } const myList = document.getElementById("list"); myList.innerHTML = listMarkup; 
 <div> <h1>Hello World!</h1> <ul id="list"></ul> </div> 

Of course, you can also use appendChild to construct the list bit by bit in the client rather than adding the whole list at once. 当然,您也可以使用appendChild在客户端中一点一点地构造列表,而不是立即添加整个列表。 This might look like: 可能看起来像:

 const myList = document.getElementById("list"); const helloWorlds = { spanish: '¡Hola Mundo!', polish: 'Witaj świecie!', french: 'Bonjour le monde!' } const helloWorldsKeys = Object.keys(helloWorlds); for (let i = 0; i < helloWorldsKeys.length; i++) { let listItem = document.createElement('li'); listItem.classList.add('listItem'); listItem.innerHTML = helloWorlds[helloWorldsKeys[i]]; myList.appendChild(listItem); } 
 <div> <h1>Hello World!</h1> <ul id="list"></ul> </div> 

Here's an example using a table: 这是一个使用表的示例:

 const myTableBody = document.getElementById("my-table-body"); const helloWorlds = { spanish: '¡Hola Mundo!', polish: 'Witaj świecie!', french: 'Bonjour le monde!' } const helloWorldsKeys = Object.keys(helloWorlds); for (let i = 0; i < helloWorldsKeys.length; i++) { // create a table row element let tableRow = document.createElement('tr'); // create a table cell (td) element let listItem = document.createElement('td'); listItem.classList.add('listItem'); // add content to table cell element listItem.innerHTML = helloWorlds[helloWorldsKeys[i]]; // append table cell to table row tableRow.appendChild(listItem); // append table row to table body myTableBody.appendChild(tableRow); } 
 <table border="1"> <thead> <td>Hello World!</td> </thead> <tbody id="my-table-body"></tbody> </table> 

Regarding your specific application, check out this answer if you want to explore creating HTML documents and appending their contents to other HTMl documents: Cannot append DOM element to DIV node: Uncaught HierarchyRequestError: Failed to execute 'appendChild' on 'Node' 关于您的特定应用程序,如果您想探索创建HTML文档并将其内容附加到其他HTMl文档,请查看此答案: 无法将DOM元素附加到DIV节点:Uncaught HierarchyRequestError:无法在“ Node”上执行“ appendChild”

The problem I see here is that you're using tbody.innerHTML = html; 我在这里看到的问题是您正在使用tbody.innerHTML = html; instead of tbody.innerHTML += html; 而不是tbody.innerHTML += html; , when you use += operator you keep the old HTML, if you use = you replace the old HTML with the new HTML ,当您使用+=运算符时,您将保留旧的HTML;如果您使用= ,则将旧的HTML替换为新的HTML

Thanks to @jaredgorski I realized why the html code was losing the formating, so this is the solution best fit my problem so far. 多亏了@jaredgorski,我才意识到为什么html代码会丢失格式,所以这是到目前为止最适合我的问题的解决方案。 Any suggestion would be appreciated. 任何建议,将不胜感激。

function convert2Element (strHTML) {
    let table = document.createElement('table');
    table.appendChild(document.createElement('tbody'));
    table.querySelector('tbody').innerHTML = strHTML;
    return table.querySelector('tbody tr');
}

Then I can append the returned value like and treat it like the object it is. 然后,我可以附加返回的值,就像对待对象一样。

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

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