简体   繁体   English

使用DOM将JavaScript数组转换为HTML表

[英]Convert javascript arrays into HTML table using DOM

I am currently creating a desktop app using tide sdk. 我目前正在使用潮汐SDK创建桌面应用程序。 All of my database information is stored into Parse.com (a serverless database). 我所有的数据库信息都存储在Parse.com(无服务器数据库)中。 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. 我想做的是获取从Parse(在javascript中)查询的信息数组,并将其插入表中。 I am really having a hard time getting used to not using document.write() for my desktop application. 我真的很难适应不为桌面应用程序使用document.write()的问题。


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. 经过一些研究后,我从http://www.w3schools.com/jsref/dom_obj_table.asp捕获了这段代码,该代码写道:屏幕左上角底部的正确响应。 (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? 有没有办法在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!!! 谢谢!!!

There are several ways to do this. 有几种方法可以做到这一点。 But from what you already have the simplest is to use innerHTML : 但是从您已经拥有的最简单的方法是使用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. 至于将表格放在页面中心,最好的方法是使用CSS。 Unfortunately centering anything in CSS is a bit of a hack. 不幸的是,将任何内容集中在CSS上都有点麻烦。 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>? 有关所有解决方法,请参见此问题的答案: 如何将<div>在另一个<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 : 关于innerHTML的一些注意事项:

  1. Although innerHTML looks like a variable it actually behaves more like a function. 尽管innerHTML看起来像一个变量,但实际上它的行为更像一个函数。 Specifically it invokes the HTML compiler of the browser. 具体来说,它调用浏览器的HTML编译器。 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. 对于某些浏览器,这意味着从DOM中删除表。 For others that means immediately inserting a closing </table> tag to make it valid. 对于其他用户,这意味着立即插入结束</table>标记使其有效。 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 . 因此,您需要传递innerHTML格式正确的html,这就是为什么我在字符串中创建表结构,然后使用innerHTML将其附加到DOM的原因。

  2. A lot of people consider innerHTML stylistically bad since you're doing DOM manipulation with strings. 很多人认为innerHTML样式上很糟糕,因为您正在使用字符串进行DOM操作。 Also because innerHTML was not originally part of any standard and was a proprietary feature of IE. 同样是因为innerHTML最初不是任何标准的一部分,而是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). 话虽如此,它可能是操作DOM的最兼容跨浏览器的方法,因为它是实现最广泛的(即使在真正的旧浏览器上)。

    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 阅读DOM API的文档,以获取有关如何“正确”执行操作的更多信息: https : //developer.mozilla.org/zh-CN/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. 正如其他人在对您的问题的评论中提到的那样,还有一些库可以使您的生活更轻松地进行DOM操作。 There are procedural libraries like jQuery that wraps the often clunky DOM API and cross-browser issues into a nice to use API. 有像jQuery这样的程序库,这些库将通常笨拙的DOM API和跨浏览器的问题包装到易于使用的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. 还有一些模板库,例如把手 ,可让您将HTML片段编写为要处理的模板并插入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. 我建议阅读DOM文档并遵循一些教程,并熟悉DOM的工作原理,并查看jQuery或YUI或下划线之类的DOM操作库,以更好地理解javascript。

Paraphrasing Douglas Crockford, you wouldn't start to program in C or Java without learning the language first. 用道格拉斯·克罗克福德(Douglas Crockford)来解释,如果不先学习语言,就不会开始用C或Java编程。 Similarly javascript is a full-featured language. 同样,javascript是功能齐全的语言。 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. javascript有很多功能,例如闭包和异步函数,它们会绊倒您。 Similarly the DOM has many behaviors that may work differently from your assumptions of how HTML works. 同样,DOM具有许多行为,这些行为可能与您对HTML的工作原理的假设有所不同。

But it is a lot to take in. So for now use innerHTML with care being aware of its limitations. 但是要花很多钱。因此,现在使用innerHTML时要注意其局限性。 Also look at document.getElementById() which is the second most used DOM API for beginners. 还要看一下document.getElementById() ,它是初学者第二常用的DOM API。 It allows you to insert your html anywhere in the document using innerHTML . 它允许您使用innerHTML将html插入文档中的任何位置 Not just the end of the document. 不只是文件的结尾。

From reading your questions I deduced the following... 通过阅读您的问题,我得出以下结论...

  1. How can I center my table using javascript. 如何使用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. 通常,在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. 尽管在jscript中方便地处理这些事情看起来不错,但如果不与节制一起使用,最终可能会炸毁您的代码。 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. 最好的选择是编写一些CSS,也许是一个通用类,该通用类可以将元素居中到页面上,然后将该类应用于table元素。 No Javascript needed, and it makes your code more modular to boot! 不需要Javascript,它使您的代码更具模块化地启动!

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.): 这是一些居中的代码,对我有用,它使注册表格div居中(可以调整高度和宽度,但是您可以根据需要调整像素的使用。):

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. 该函数创建一个表,为其设置一个ID,然后将其添加到文档中,然后创建一个新行,同时为其设置一个ID,然后将新行添加到该表中。 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. 然后,您进入一个受query4长度限制的for循环(我假设这是包含您的联系信息的查询),并创建文本节点,每次迭代都将它们附加到z(单元格),如果我没有记错的话,实际上导致第一行(也是唯一行)中的单元格被所有查询信息炸毁。 What should be happening is the for loop adds the name and number to its own cells in a NEW row each iteration. 应该发生的是,for循环在每次迭代时将名称和编号添加到其自己的单元格中的NEW行中。 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.) (查看本书“ Clean Code”,它详细讨论了这一点,它几乎在一夜之间改变了我查看代码的方式。)

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. 另一件事,我假设可以在全局范围内设置query4变量,该变量将起作用,但是通常最好尝试保持全局空间是否可用以及何时可用。 (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? (请参阅Douglas Crockfords的另一本关于Javascript的好书,《 Javascript:The Good Parts》确实帮助我学习了该语言。)也许考虑将数据传递给generate表函数,并在解析数据返回的回调中调用该函数?

Anyway, that is my "brief" two cents, hope it helps! 无论如何,那是我的“简短”两分钱,希望对您有所帮助!

Good luck. 祝好运。

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

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