Convert javascript arrays into HTML table using DOM

做~自己de王妃 提交于 2019-12-25 01:38:09

问题


I am currently creating a desktop app using tide sdk. All of my database information is stored into Parse.com (a serverless database). What I am trying to do is to take the array of the information I queried from Parse (in javascript) and insert it into a table. I am really having a hard time getting used to not using document.write() for my desktop application.


I want the end result to look like:


This is what I started with:

var contactNameArray = [];
var contactNumberArray= [];
var CM = Parse.Object.extend("ContactMenu");
var queryContact = new Parse.Query(CM);
queryContact.ascending("ContactName");
queryContact.find({
  success: function(results4) {
    alert("Successfully retrieved " + results4.length + " entries.");
    // Do something with the returned Parse.Object values
// document.write('<table border="1" cellspacing="1" cellpadding="5">');
    for (var i = 0; i < results4.length; i++) {
      var object4 = results4[i];
      contactNameArray[i] = object4.get('ContactName');
      contactNumberArray[i] = object4.get('ContactNumber');
 // document.write("<tr><td>Number " + i + " is:</td>");
  //document.write("<td>" + contactNameArray[i] + "</td></tr>");

    }

//document.write('</table>');
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});

After doing some research I cam upon this bit of code from http://www.w3schools.com/jsref/dom_obj_table.asp which wrote: the correct response on the bottom of the left handed corner of the screen. (Kind of strange in my opinion). In code how can I better position this table to be in the center for my screen? Is there a way to center this table in javascript?

function generate_table() {
 var x = document.createElement("TABLE");
    x.setAttribute("id", "myTable");
    document.body.appendChild(x);

    var y = document.createElement("TR");
    y.setAttribute("id", "myTr");
    document.getElementById("myTable").appendChild(y);
    var z = document.createElement("TD");

    for(var i = 0; i< query4.length; i++){

       var t = document.createTextNode(contactNameArray[i]);
       z.appendChild(t);
       var m = document.createTextNode(contactNumberArray[i]);
       z.appendChild(m);
    }
    document.getElementById("myTr").appendChild(z);
}

So I have already figured out how to put the information I want into an array. I am just having a hard time putting this information into a table that is correctly positioned. Thank you in advance. If you need to see any more of my code, then just let me know. If I am unclear, please let me know what I should explain. Thank you!!!


回答1:


There are several ways to do this. But from what you already have the simplest is to use innerHTML:

queryContact.find({
  success: function(results4) {
    var html = "";
    alert("Successfully retrieved " + results4.length + " entries.");
    // Do something with the returned Parse.Object values
    html += '<table border="1" cellspacing="1" cellpadding="5">';
    for (var i = 0; i < results4.length; i++) {
      var object4 = results4[i];
      contactNameArray[i] = object4.get('ContactName');
      contactNumberArray[i] = object4.get('ContactNumber');
      html += "<tr><td>Number " + i + " is:</td>";
      html += "<td>" + contactNameArray[i] + "</td></tr>";

    }

    html += '</table>';
    document.body.innerHTML += html;
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});

As for centering the table on the page the best way is to use CSS. Unfortunately centering anything in CSS is a bit of a hack. There are several ways to do it. See the answers to this question for all the ways of doing it: How to horizontally center a <div> in another <div>?. Note: scroll through the answers, not just read the top one. There really are a lot of ways to do this and some may not work for you.

A few notes about innerHTML:

  1. Although innerHTML looks like a variable it actually behaves more like a function. Specifically it invokes the HTML compiler of the browser. So if you pass it incomplete tags like:

    someDiv.innerHTML += '<table>';
    

    it will see that as an incomplete 'table' tag and deals with it the way the browser usually does when it sees an incomplete 'table' tag. For some browsers that means removing the table from the DOM. For others that means immediately inserting a closing </table> tag to make it valid. What this means is that when you later append the closing tag like this:

    someDiv.innerHTML += '</table>';
    

    what happens is that the browser will think you did this:

    <table></table></table>
              ^       ^
              |       |_________ what you're trying to insert
              |
       auto inserted by the browser earlier
    

    and deal with it the way browsers usually do - consider that tag invalid and discard it.

    So you need to pass innerHTML well-formed html which is why I created the table structure in a string then append it to the DOM with innerHTML.

  2. A lot of people consider innerHTML stylistically bad since you're doing DOM manipulation with strings. Also because innerHTML was not originally part of any standard and was a proprietary feature of IE. Since it's not part of any standard there's no real agreement between different browsers for how it should work. Having said that, it's probably the most cross-bowser compatible method of manipulating DOM because it's the most widely implemented (even on really old browsers).

    Read the documentation of the DOM API for more info on how to do it "properly": https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model

  3. As mentioned by others in the comment to your question, there are also libraries out there that would make your life easier for DOM manipulation. There are procedural libraries like jQuery that wraps the often clunky DOM API and cross-browser issues into a nice to use API. There are also templating library like handlebars that allows you to write the HTML fragments as templates to be processed and inserted into the DOM.

I suggest getting comfortable with how the DOM works by reading the DOM documentation and follow some tutorial and also look at DOM manipulation libraries like jQuery or YUI or underscore to get a better feel of javascript.

Paraphrasing Douglas Crockford, you wouldn't start to program in C or Java without learning the language first. Similarly javascript is a full-featured language. Take some time to learn it and not just assume that "it works like [insert a language you know]". There are many features of javascript like closures and asynchronous functions that will trip you up. Similarly the DOM has many behaviors that may work differently from your assumptions of how HTML works.

But it is a lot to take in. So for now use innerHTML with care being aware of its limitations. Also look at document.getElementById() which is the second most used DOM API for beginners. It allows you to insert your html anywhere in the document using innerHTML. Not just the end of the document.




回答2:


From reading your questions I deduced the following...

  1. How can I center my table using javascript.

  2. I am having an issue getting my information into a table.

Typically it is not a good idea to do styling within your javascript. While it may seem nice to handle such things conveniently within your jscript, it can end up blowing up your code if not used with moderation. Your best bet would be to write some css, perhaps a generic class that can center an element to a page, and then apply this class to the table element. No Javascript needed, and it makes your code more modular to boot!

Here is a hacky bit of centering code that has worked for me to center a registration form div (Height and Width can be adjusted however you like, use of pixels is not a must.):

body > #register {
  margin: auto;
  position: absolute;
  text-align: center;
  height: 156px;
  width: 160px;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

For the issues you are experiencing adding information to your table, without knowing what errors or exact output your are seeing, all I can do is go off what I can see in the code. Your generate table function has a few areas I noticed....

The function creates a table, sets an id to it, and appends it to the document, it then creates a new row, setting an id to it as well, it then appends the new row to the table. Then a cell is created.

Here is where I see a problem...

You then jump into a for loop limited by the length of query4 (I'll assume this is the query containing your contact info) and create text nodes, appending them to z (the cell) each iteration, if I am not mistaken that would actually result in the cell in the first(and only) row getting blown up with all your query info. What should be happening is the for loop adds the name and number to its own cells in a NEW row each iteration. This would be your psuedocode...

  • Create table
  • Start for loop over contact info for each item...
    • Create new row
    • Create new cells
    • add info to respective cells
    • append cells to row
    • append row to table
    • rinse and repeat

Based on what you have, here is a rough untested representation of what I am suggesting, I built it out of your own code, but it could be done in several ways really...

 function generate_table() {

    // Create our table
    var table = document.createElement("TABLE");
    document.body.appendChild(table);

    for(var i = 0; i < query4.length; i++) {
       // Set up an awesome new row.
       var row = document.createElement("TR");

       // Set up awesome new cells.
       var nameCell = document.createElement("TD");
       var numberCell = document.createElement("TD");

       // Instantiate variables to hold our data.
       var name = document.createTextNode(contactNameArray[i]);
       var number = document.createTextNode(contactNumberArray[i]);

       // Add values to cells
       nameCell.appendChild(name);
       numberCell.appendChild(number);

       // Add cells to row.
       row.appendChild(name);
       row.appendChild(number);

       // Build out awesome row.
       table.appendChild(row);
    }
}

I did a couple things here, first off some variable renaming, descriptive variable names do wonders for code readability and maintenance later on. (Check out the book "Clean Code", it talks on this at length, it changed the way I look at code virtually overnight.)

One other thing, I assume the query4 variable is being set up in the global scope, that will work, but it's typically good to try an keep the global space clear if and when you can. (See Douglas Crockfords "Javascript: The Good Parts", another great book on Javascript that really helped me learn the language.) Maybe consider passing the data to the generate table function, and calling the function in the callback of the parse data return?

Anyway, that is my "brief" two cents, hope it helps!

Good luck.



来源:https://stackoverflow.com/questions/25373281/convert-javascript-arrays-into-html-table-using-dom

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