简体   繁体   English

Javascript,表格和数组。 棘手的问题

[英]Javascript, table and array. tricky issue

I'm making a bookshop website (for a little college javascript project) So far all my book info is in arrays in a .js file which looks like this.. 我正在建立一个书店网站(用于一个大学的小javascript项目),到目前为止,我所有的图书信息都是以.js文件的数组形式出现的。

var headings  = new Array(4);
headings [0] = "title"
headings [1] = "author"
headings [2] = "cat"
headings [3] = "bookid"
headings [4] = "cost"

var bookid   = new Array(6);
var title   = new Array(6);
var cat  = new Array(6);
var author  = new Array(6);
var cost  = new Array(6);
var desc  = new Array(6);

bookid [0] = "0001"
title [0]    = "For whom the tell bowls";
cat[0]   = "fiction";
author[0]   = "John Doe";
cost[0]   = "€12.99";
desc[0]   = "This book is frickin' amazing blah blah blah"

and so on... there are 7 books... 依此类推...共有7本书...

Now I want to generate a table when I click on a thumbnail pic which has the author, title, cost etc. in one column and the actual corresponding details in the other column, Heres the code 现在,我想生成一个表,当我单击缩略图图片时,该图片的一列中包含作者,标题,费用等,而另一列中包含实际的相应详细信息,这是代码

for(var j = 0; j < 5; j++) {
                row = document.createElement("tr");

                // Each with 2 cells
                for(var i = 0; i < 2; i++) {

                    var cell = document.createElement("td");

                    var temp = headings[j];
                    var temp2 = (temp + '[' + filename + ']');
                    if (i==1)
                    {var text = document.createTextNode(temp2);
                    }
                    else 
                    {var text = document.createTextNode(temp);}

btw "filename" is passed to this function and it is the #of the book, eg, 0, 1, 2 and so on... Now, what displays on the page is sorta correct.. for book 0 I get.. btw“文件名”传递给此函数,它是书的#号,例如0、1、2等...现在,页面上显示的内容是正确的..对于我得到的书0。

title   title[0]
author  author[0]
cat         cat[0]
bookid  bookid[0]
cost    cost[0]

and for book 1 I get 对于第一本书,我得到了

title   title[1]
author  author[1]
cat         cat[1]
bookid  bookid[1]
cost    cost[1]

and so on, but details are not being interpreted as actual variables in an array. 等等,但是细节不会被解释为数组中的实际变量。 I'm guessing the solution has something to do with "innerHTML" or maybe casting my variables in some way.. 我猜测该解决方案与“ innerHTML”有关,或者可能以某种方式转换了我的变量。

If someone knows the solution to this it would be greatly appreciated!.. I'm planning to get this site finished today and move onto to something else more important (as this project is not worth many marks) But leaving this flaw in there would bug me! 如果有人知道解决方案,将不胜感激!..我计划今天完成此站点,然后移至更重要的其他位置(因为该项目不值得很多标记),但是在这里留下这个缺陷将来烦我!

The way you're tackling this problem right now is (trying to) access a variable by its name, eg you want to use "title" to find the variable named title . 您现在解决此问题的方法是(尝试)按名称访问变量,例如,您想使用"title"查找名为title的变量。 Do not do this. 不要这样做。 You'll either end up polluting the global scope and relying on window to access those variables, or you'll fall in the hand of the eval devil . 您要么会污染全局范围并依靠window来访问这些变量,要么会落入eval魔鬼之手。

Here's a better idea: make objects to store your books. 这是一个更好的主意:制作对象来存储您的书籍。 A book would then look like: 这样一本书看起来像:

var book = {
    title: "Foo",
    author: "Bar",
    cat: "Baz",
    bookid: 123456,
    cost: "One hundred billion dollars"
};

Even better would be to define a type of books: 更好的方法是定义一种书籍:

function Book(title, author, cat, bookid, cost) {
    this.title = title;
    this.author = author;
    this.cat = cat;
    this.bookid = bookid;
    this.cost = cost;
}
var book = new Book("Foo", "Bar", "Baz", 123456, "One hundred billion dollars");

You could store these books into a single book array: 您可以将这些书存储到单个书数组中:

var books = [book1, book2, book3, ...];

and suddenly, it becomes easy to make a table! 突然之间,制作桌子变得容易了!

// Create or get a table
var table = document.createElement("table");

// Loop over the books array
for (var i=0, l=books.length; i < l; ++i) {
    // Get the current book
    var book = books[i];

    // Create a table row
    var row = document.createElement("tr");

    // Loop over the *properties* of the book
    for (var propertyName in book) {
        // Skip inherited properties
        if(!book.hasOwnProperty(propertyName)) continue;

        // Get the *property value*
        var property = book[propertyName];

        // Create a table cell and append to the row
        var textNode = document.createTextNode(property);
        var cell = document.createElement("td");
        cell.appendChild(textNode);
        row.appendChild(cell);
    }
    // Append the row to the table
    table.appendChild(row);
}

You could even create the table headings using one book element: 您甚至可以使用一个book元素创建表标题:

// Some book to loop over its property names
var someBook = books[0];

var row = document.createElement("tr");
// Loop over the book properties
for(var propertyName in someBook) {
    // Now placing the *property name* in a text node
    var textNode = document.createTextNode(propertyName);
    var header = document.createElement("th");
    cell.appendChild(textNode);
    row.appendChild(header);
}
table.appendChild(row);

Update: Better control over the headings 更新:更好地控制标题

As Dennis suggested, you probably want more control over the headings. 正如丹尼斯建议的那样,您可能希望对标题进行更多控制。 You don't want to display "cat" as the heading for the book's category, you want something more readable. 您不想将"cat"显示为书籍类别的标题,而是想要更具可读性的内容。 Also, you probably don't want to display all properties stored on a book object. 另外,您可能不想显示存储在book对象上的所有属性。 In this case, you could store the headings to display in another object and add some more information about those headings: 在这种情况下,您可以存储要显示在另一个对象中的标题,并添加有关这些标题的更多信息:

var headings = {
    title: {
        text: "Book title"
    },
    author: {
        text: "Author"
    },
    cat: {
        text: "Category"
    },
    bookid: {
        text: "ID"
    },
    cost: {
        text: "Price"
    }
};

In your data loop, you would then iterate over the properties of headings instead of book . 然后,在数据循环中,您将遍历headings的属性而不是book

// Loop over the properties to display
for (var propertyName in headings) {
    // Get the property value
    var property = book[propertyName];

    // [snipped]
}

In your headings loop, you would use headings[propertyName].text as display name instead of just propertyName . 在标题循环中,您将使用headings[propertyName].text作为显示名称,而不仅仅是propertyName You won't need a book instance any longer, so the someBook variable can be removed. 您不再需要一个书实例,因此可以删除someBook变量。

// Loop over the book properties
for(var propertyName in headings) {
    var headingName = headings[propertyName].text;
    var textNode = document.createTextNode(headingName);

    // [snipped]
}

Your problem is here: 您的问题在这里:

var temp2 = (temp + '[' + filename + ']');

You are concatenating strings; 您正在连接字符串; instead of the JavaScript statement title[1] , you end up with the string "title[1]" . 而不是JavaScript语句title[1] ,您最终得到了字符串"title[1]"

What you should do is create an object using a constructor function and build an array of objects instead of maintaining several parallel arrays : 您应该做的是使用构造函数创建一个对象并构建一个对象数组,而不是维护多个并行数组

function Book(title, author, cat, id, cost) {
    this.title = title;  //for each variable
}

var arrayOfBooks = [];
arrayOfBooks.push( new Book( "The Great Gatsby", "F. Scott Fitzgerald", "Fiction", 1, 5000.00));
//and so on for each book.

When you build your table: 建立表格时:

var book = arrayOfBooks[filename];
var temp = headings[j];
var temp2 = book[temp]; //Use brackets instead of concatenating strings.

Another tip: the inner loop is unnecessary if you are just toggling with an if statement anyway. 另一个提示:无论如何,只要切换if语句,就不需要内部循环。 You could just create two cells and put the necessary text values in each. 您可以只创建两个单元格,然后在每个单元格中放置必要的文本值。

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

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