Create an element using javascript

只谈情不闲聊 提交于 2021-01-27 16:33:07

问题


I have a html table

<table id = "rpttable" name = "rpttable">
  <thead>
    Column Headers here...
  </thead>
  <tbody id = "rptbody" name = "rptbody">
    data here <3 ....
  </tbody>
</table>

and here is my php (sample.php)

<?php
  Query Code here..
  Query Code there..
  and so on

  //this is the way I populate a table
  while (query rows) {
    echo '<tr>';
    echo '<td>Sample Data</td>';
    echo '</tr>;
  }
?>

So to make this work and to populate the table this is what I do.

<table id = "rpttable" name = "rpttable">
  <thead>
    Column Headers here...
  </thead>
  <tbody id = "rptbody" name = "rptbody">
    <?php
       include 'folder_location/sample.php';
    ?>
  </tbody>
</table>

Disregard the image of the ouput but when I go to Inspect Element or even Ctrl + u I will see my table structure now is like this.

<table id = "rpttable" name = "rpttable">
  <thead>
    Column Headers here...
  </thead>
  <tbody id = "rptbody" name = "rptbody">
    <tr>
    <td>Sample Data</td>
    </tr>
  </tbody>
</table>

Now here is the thing. I do not do that this is what I do.

$("#rpttable tr").remove();
        for (i = 0; i < data.length; i++) {
            tr = $("<tr />");
            for (x in data[i]) {
                td = $("<td />");
                td.html(data[i][x]);
                tr.append(td);
            }
            rpttable.append(tr);                    
        }

Same output It does populate the table but when I go to Inspect Element or even Ctrl + u the output is.

<table id = "rpttable" name = "rpttable">
  <thead>
    Column Headers here...
  </thead>
  <tbody id = "rptbody" name = "rptbody">
    **This is the part missing**
  </tbody>
</table>

My question here is how can I literaly create an element usung javascript/ajax? same output in php. I mean write the element.

** Updated ** I am trying to run a css class from an external file and If I manualy edit it to suits my needs I will a long hour and also Its hard for me to explain its a class for table. I tried to use that class using default value in <table>. You know manualy write it at the back end. now Im trying to populate it using a php and ajax so, so far so good it does populate but when I try to run the class the class does not work.

TYSM


回答1:


Using jquery you can add html rows to the tbody using:

$("#rptbody").html("<tr><td>value</td></tr>");

Is this what you want to do?




回答2:


You can use JQuery append() method:

$('#rptbody').append('<tr><td>my data</td><td>more data</td></tr>');

In case you need to insert after last row:

$('#rptbody> tbody:last-child').append('<tr>...</tr><tr>...</tr>');



回答3:


 for (i = 0; i < 5; i++) {
     let tr = $("<tr />");
      for (j=0; j < 5;j++)
         tr.append($("<td />",{html:j,class:"tbl"}));
      $("tbody").append(tr);                    
}
.tbl{border:1px solid pink;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody></tbody>
</table>



回答4:


You have asked roughly two questions. Let's break it down.

My question here is how can I literaly create an element usung javascript/ajax?

You are already doing this with your Javascript (client-side) code. It looks like you're using jQuery syntax, so we'll stick with that. This does create an element and inserts it into the page.

var $el = $("<div>I'm a new div element</div>");
$('body').append( $el );

This creates a new element, assigns it to the $el variable, and then appends it to the body of the page. This will not show up in "View Page Source" view, however. Why? Because this modifies the DOM -- the Dynamic Object Model.

To see this new element, you'll either need to look at the rendered output (what the user/you sees), or open up your browser's DevTools (often <F12>, or right-click -> inspect). In the DevTools, find the "Inspector" tab (or equivalent), then look for your new element in this live view of the DOM.

... same output in php.

In short, you can't. What Ctrl+U / View Page Source shows is the page as it was initially received from the server. This would be the exact content you would see if you were to use a command line tool, like curl or wget:

curl http://url.to.your.com/page

Since you include 'folder_location/sample.php' at the server, this is included in the page before the browser sees it. For your edification, I would consider reading up on the DOM.

  • Wikipedia
  • W3



回答5:


Try this:

$("#rpttable tbody tr").remove();
var content = '' ;
for (i = 0; i < data.length; i++) {
    content += "<tr>" ;

    for (x in data[i]) {
        content += "<td>" + data[i][x] + "</td>" ;
    }

    content += "</tr>" ;
}

$("#rpttable tbody").html(content) ;

Updated

I am using Google Chrome too. Please try the below code, and check the inspect element each time you add a new row. You can see the html in the Inspect Element changing!

function AppendNewRowToTable() {
  var trLen = $("table tbody tr").length ;

  var content = "" ;

  content += "<tr>" ;
  for (i = 0; i < 5; i++) {
        content += "<td>" + trLen + "-" + i + "</td>" ;
    }
  content += "</tr>" ;

  $("table tbody").append(content) ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="javascript:;" onclick="AppendNewRowToTable()">Add new Row</a>
<br />

<table>
  <thead>
    <tr>
      <th>Title 01</th>
      <th>Title 02</th>
      <th>Title 03</th>
      <th>Title 04</th>
      <th>Title 05</th>
    </tr>
  </thead>

  <tbody></tbody>
</table>



回答6:


It seems your intent is to append extra rows to the table in your html response generated from your PHP script.

For that you don't need to clear all existing rows.

$("#rpttable tr").remove();

Build an array of rows and append once to your table body.

var $tbody = $('#rptbody');
var tableRowAdditions = [];

for (var i = 0; i < data.length; i++) {
  var $tr = $("<tr></tr>");

  for (var x in data[i]) {
     var $td = $("<td></td>");
     $td.html(data[i][x]);
     $tr.append(td);
  }
  tableRowAdditions.push(tr);                   
}

$tbody.append(tableRowAdditions);



回答7:


For a "pure" JavaScript approach, you can create elements using the createElement Web API

For example: A paragraph with text "Hello" would be

var container = document.getElementById('rptbody');
var hello = document.createTextNode('Hello');
var helloParagraph = Document.createElement('p');
// Add text to paragraph
helloParagraph.appendChild(hello);
// Append to container
container.appendChild(helloParagraph);



回答8:


The best way to create elements using jQuery is to use the following format:

// Create the TR and TD elements as jQuery objects.

var tr = $("<tr></tr>", {
  "id":"tr1",
  "class":"tr"
});

var td = $("<td></td>", {
  "id":"td1",
  "class":"td",
  "text": "Sample Data",
  click: function() {
    // optional: Function to attach a click event on the object
    alert("Clicked!");
  }
});

// Attach the element to the document by appending it 
// inside rptbody (after all existing content inside #rptbody) 
$("#rptbody").append(tr);
tr.append(td);

// OR, Attach the element to the document by prepending it
// inside rptbody (before all existing content in #rptbody) 
$("#rptbody").prepend(tr);
tr.append(td);

// OR, Attach the element to the document by completely replacing the content of #rptbody
$("#rptbody").html(tr);
tr.append(td);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "rpttable" name = "rpttable">
  <thead>
    Column Headers here...
  </thead>
  <tbody id = "rptbody" name = "rptbody">
  </tbody>
</table>


来源:https://stackoverflow.com/questions/46681037/create-an-element-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!