使用DOM将JavaScript数组转换成HTML表 [英] Convert javascript arrays into HTML table using DOM

查看:161
本文介绍了使用DOM将JavaScript数组转换成HTML表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用潮汐sdk创建一个桌面应用程序。我的所有数据库信息都存储在Parse.com(无服务器数据库)中。我想要做的是使用从Parse(在javascript中)查询的信息的数组,并将其插入到表中。我真的很难习惯于对我的桌面应用程序使用document.write()。

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.

我想要最终结果如下:

这是我开始的:

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);
  }
});






做了一些研究后,我凸显了这一点来自 http://www.w3schools.com/jsref/dom_obj_table.asp 的代码,其中写道:屏幕左手角底部的正确答案。 (在我看来,奇怪的种类)。在代码中,如何更好地将此表置于屏幕中央?有没有办法将此表格放在javascript中?


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!!!

推荐答案

有几种方法可以做到这一点。但是从你已经最简单的是使用 innerHTML

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);
  }
});

对于在页面上居中的最佳方式是使用CSS。不幸的是,在CSS中的任何东西都是一个黑客。有几种方法可以做到。有关这方面的所有方法,请参阅此问题的答案:如何水平居中< div>在另一个< div>?。注意:滚动浏览答案,而不只是读取顶部的答案。真的有很多方法可以做到这一点,有些可能不适合你。

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.

关于 innerHTML


  1. 虽然 innerHTML 看起来像一个变量,像一个功能。具体来说,它调用浏览器的HTML编译器。所以如果你传递不完整的标签,例如:

  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>';

它会看到一个不完整的表标签,并以浏览器通常的方式处理当它看到一个不完整的表标签。对于某些浏览器,意味着从DOM中删除表。对于其他人,这意味着立即插入关闭< / 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.

所以你需要通过 innerHTML 格式正确的html,这就是为什么我创建字符串中的表结构将其附加到具有 innerHTML 的DOM中。

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 风格不好,因为您使用字符串进行DOM操作。另外因为 innerHTML 不是任何标准的一部分,而是IE的专有功能。由于它不属于任何标准,因此不同浏览器之间没有真正的协议。话虽如此,它可能是操作DOM的最多的cross-bowser兼容方法,因为它是最广泛实现的(即使是真正的旧浏览器)。

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).

阅读文档DOM API了解更多有关如何做到这一点的信息正确: https: //developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model

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操作。有像 jQuery 这样的过程图书馆,将经常笨重的DOM API和跨浏览器问题包装在一个很好的API中。还有一些模板库,如句柄,允许您将HTML片段编写为要处理并插入DOM的模板

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.

我建议您通过阅读DOM文档来了解DOM的工作原理,并遵循一些教程,并查看DOM操作库,如jQuery或YUI或下划线,以获得更好的JavaScript感觉。

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.

释义道格拉斯·克罗克福德,您不会开始在C或Java中编程,而无需学习语言第一。同样,JavaScript是一个全功能的语言。花一些时间来学习它,而不只是假设它的工作原理就像[插入你所知道的语言]。有很多javascript的关闭和异步功能的功能,将会让你失望。类似地,DOM有许多行为可能与您对HTML的工作原理有所不同。

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.

但是很多事情要付诸实施,所以现在使用 innerHTML 小心意识到它的局限性。另请查看 document.getElementById()这是初学者使用第二大DOM API。它允许您使用 innerHTML 在文档中的任何位置中插入您的HTML。不仅仅是文档的结尾。

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.

这篇关于使用DOM将JavaScript数组转换成HTML表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆