Separation of Javascript and Html when dynamically adding html via javascript

I am currently creating a very dynamic table for a list application that will basically perform basic CRUD functions through AJAX.

What I would like to do is separate visual design and javascript to such an extent that I can change the design side without touching the JS side. This will only work where the design remains roughly the same (I would like to use it to quickly create prototypes).

Here is an example.

<table>
<tr><td>record-123</td><td>I am line 123</td><td>delete row</td></tr>
<tr><td>record-124</td><td>I am line 124</td><td>delete row</td></tr>
<tr><td>record-125</td><td>I am line 125</td><td>delete row</td></tr>
<tr><td>add new record</td></tr>
</table>

Now when I add a new entry, I would like to insert a new html line, but I would prefer not to put this html in a javascript file.

What I am considering creates such a row on the page next to the table.

<tr style='visble:none;' id='template-row'><td>record-id</td><td>content-area</td><td>delete row</td></tr>

, , id = template-row, , , .

, - , , js.

- ?

+3
2

Micro-Templating John Resig.

:

<script type="text/html" id="row_tmpl">
    <tr><td><%=id%></td><td><%=content%></td><td>delete row</td></tr>
</script>

<script type="text/javascript" src="templating.js"></script>
<script type="text/javascript">
    (function(){
       var dataObject = {"id":"myid","content":"some content"};
       var html = tmpl("row_tmpl", dataObject);
       // do whatever you want with the new HTML...
    }());
</script>


SO, XSS, , , . javascript <% %> . , , , <% %>.

+6

, , .

? , DOM node. node HTML, DOM node. , , HTML.

cloneNode, DOM, .

<style type="text/css">
    .hidden { display: none; }
</style>

<table id="sometable">
    <tr class="hidden"><td>-</td><td>-</td><td>delete row</td></tr>
</table>
<input type="button" id="sometable-newrow" value="New row"/>

<script type="text/javascript">
    var recordn= 1;

    document.getElementById('sometable-newrow').onclick= function() {
        var table= document.getElementById('sometable');
        var tr= table.rows[0].cloneNode(true);

        tr.className= ''; // remove hiddenness
        tr.cells[0].firstChild.data= 'record-'+recordn;
        tr.cells[1].firstChild.data= 'I am line '+recordn;
        tr.cells[2].onclick= removeRow;

        table.rows[table.rows.length-1].parentNode.appendChild(tr);
        recordn++;
    };

    function removeRow() {
        var tr= this.parentNode;
        tr.parentNode.removeChild(tr);
    }
</script>
+1

Source: https://habr.com/ru/post/1740917/


All Articles