jquery选择器迭代子级,然后迭代父级/同级

发布于 2024-11-30 11:34:49 字数 1303 浏览 1 评论 0原文

我有以下简化的 HTML。

<div id="coat">
<span class="Jan2011-Sales">10</span>
<span class="Feb2011-Sales">10</span>
<span class="Mar2011-Sales">10</span>
</div>

<div id="boot">
<span class="Jan2011-Sales">10</span>
<span class="Feb2011-Sales">10</span>
<span class="Mar2011-Sales">10</span>
</div>

<div id="hat">
<span class="Jan2011-Sales">10</span>
<span class="Feb-Sales">10</span>
<span class="Mar2011-Sales">10</span>
</div>

<div id="etc.">
</div>

编辑:

我想做的是创建一个如下表:(几乎像数据透视表)

   <th>
       <td>Period</td>
       <td>Coat</td>
       <td>Boot</td>
       <td>Hat</td>
   </th>
   <tr>
       <td>Jan2011-Sales</td>
       <td>10</td>
       <td>10</td>
       <td>10</td>
   <tr>
   <tr>
       <td>Feb2011-Sales</td>
       <td>10</td>
       <td>10</td>
       <td>10</td>
   <tr>
   etc.

我的问题是——如何迭代原始 HTML? 例如,我的想法是迭代第一个元素以获取行,然后获取父级的同级 div,以便我可以找到/匹配其子级以获取列。

想法? 谢谢。

I have the following simplified HTML Below.

<div id="coat">
<span class="Jan2011-Sales">10</span>
<span class="Feb2011-Sales">10</span>
<span class="Mar2011-Sales">10</span>
</div>

<div id="boot">
<span class="Jan2011-Sales">10</span>
<span class="Feb2011-Sales">10</span>
<span class="Mar2011-Sales">10</span>
</div>

<div id="hat">
<span class="Jan2011-Sales">10</span>
<span class="Feb-Sales">10</span>
<span class="Mar2011-Sales">10</span>
</div>

<div id="etc.">
</div>

EDITED:

What I'd like to do is create a table like below: (almost like a pivot table)

   <th>
       <td>Period</td>
       <td>Coat</td>
       <td>Boot</td>
       <td>Hat</td>
   </th>
   <tr>
       <td>Jan2011-Sales</td>
       <td>10</td>
       <td>10</td>
       <td>10</td>
   <tr>
   <tr>
       <td>Feb2011-Sales</td>
       <td>10</td>
       <td>10</td>
       <td>10</td>
   <tr>
   etc.

My question is -- how do I iterate over the original HTML?
e.g. my thinking is along the lines of iterating over the first elements to get the rows, then getting the parent's sibling div so that I can find/match its child to get the columns.

Thoughts?
THank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北恋 2024-12-07 11:34:49

这是一个 jsFiddle,它获取 HTML 数据并从中创建表格: http://jsfiddle.net/jfriend00/ RKBAj/

做出以下假设:

  1. 文档中的每个顶级 div 都是一个产品
  2. 每个顶级 div 都有一个代表产品名称的 ID 顶级
  3. div 中的每个 span 都是一个月 顶级 div
  4. 中的每个 span 都有一个代表产品的类name
  5. 跨度的innerHTML 是该产品/月的数据
  6. 产品名称可以是任何名称(尽管它们只能是CSS ID 的合法字符)。
  7. 月份名称可以是任何名称(尽管它们只能是 CSS 类的合法字符)。
  8. 可以有任意数量的月份和产品。
  9. 每个产品可以有任意数量的月份。
  10. 所有产品不一定具有相同的月份。

然后,您可以通过以下方式迭代数据并将所有数据收集到有组织的数据结构中,并从中构建表。

// iterate over divs which we assume are products
var allProducts = [];
var allMonthsOrder = [];
function parseData() {
    $("body > div").each(function() {
        var allMonthsKey = {};
        var product = {};
        product.name = this.id;
        product.months = {};
        // now iterate each month in this product
        $("span", this).each(function() {
            var month = this.className;
            product.months[month] = this.innerHTML;
            // add unique months to the month array (only if we haven't seen it before)
            if (!allMonthsKey[month]) {
                allMonthsKey[month] = true;
                allMonthsOrder.push(month);     // store these in order encountered
            }
        });
        allProducts.push(product);
    });
}


// data is stored now in allProducts array
// one array element for each product
// each product is an object with a .name attribute and a .months attribute
// each .months attribute is an object where each attribute is a month name and the data for that month

数据的存储方式如下:

allProducts = [
    {
        "name": "coat", 
        "months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"}, 
        ]
    },
    {
        "name": "boot", 
        "months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"}, 
    },
    {
        "name": "hat", 
        "months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"}, 
    }
];

而且,这是从数据创建表的一种方法。生成表的棘手部分是,如果任何产品可以有任意数量的月份,并且所有产品不一定具有相同的月份,那么您必须为存在的每个月份创建一行,并填写产品数据(如果有)该月的数据。

function createTable() {
    var i, j, product, month;
    var html = "<table><tr>";
    // iterate over the product names to make the header row
    html += "<th>Month</th>";
    for (i = 0; i < allProducts.length; i++)
        html += "<th>" + allProducts[i].name + "</th>";
    }
    html += "</tr">

    // now create all the rows.  First column is month, then each column after that is the sales for 
    // a given month for a particular product (one product per columnn)

    for (i = 0; i < allMonthsOrder.length; i++) {
        month = allMonthsOrder[i];
        html += "<tr>" + "<td>" + month + "</td>";
        // iterate through each product and find if it has data for this month
        for (j = 0; j < allProducts.length; j++) {
            product = allProducts[j];
            html += "<td>";
            if (product.months[month]) {
                html += product.months[month];
            }
            html += "</td>";
        }
        html += "</tr>";
    }
    html += "</table>";
}

Here's a jsFiddle that takes your HTML data and make a table out of it: http://jsfiddle.net/jfriend00/RKBAj/.

Making these assumptions:

  1. Every top level div in the document is a product
  2. Every top level div has an ID that represents the product name
  3. Every span in the top level div is a month
  4. Every span in the top level div has a class that represents the product name
  5. The innerHTML of the span is the data for that product/month
  6. Product names can be anything (though they have to be made only our legal characters for a CSS ID).
  7. Month names can be anything (though they have to be made only our legal characters for a CSS class).
  8. There can be as many months and products as you want.
  9. Each product can have any number of months.
  10. All products don't necessarily have the same months.

Then, here's how you could iterate over the data and collect all the data into an organized data structure from which you could build a table.

// iterate over divs which we assume are products
var allProducts = [];
var allMonthsOrder = [];
function parseData() {
    $("body > div").each(function() {
        var allMonthsKey = {};
        var product = {};
        product.name = this.id;
        product.months = {};
        // now iterate each month in this product
        $("span", this).each(function() {
            var month = this.className;
            product.months[month] = this.innerHTML;
            // add unique months to the month array (only if we haven't seen it before)
            if (!allMonthsKey[month]) {
                allMonthsKey[month] = true;
                allMonthsOrder.push(month);     // store these in order encountered
            }
        });
        allProducts.push(product);
    });
}


// data is stored now in allProducts array
// one array element for each product
// each product is an object with a .name attribute and a .months attribute
// each .months attribute is an object where each attribute is a month name and the data for that month

The data is stored like this:

allProducts = [
    {
        "name": "coat", 
        "months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"}, 
        ]
    },
    {
        "name": "boot", 
        "months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"}, 
    },
    {
        "name": "hat", 
        "months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"}, 
    }
];

And, this is one way you could create your table from the data. The tricky part of generating the table is that if any product can have any number of months and all products don't necessarily have the same months, then you have to make a row for every month that exists and fill in product data if it has data for that month.

function createTable() {
    var i, j, product, month;
    var html = "<table><tr>";
    // iterate over the product names to make the header row
    html += "<th>Month</th>";
    for (i = 0; i < allProducts.length; i++)
        html += "<th>" + allProducts[i].name + "</th>";
    }
    html += "</tr">

    // now create all the rows.  First column is month, then each column after that is the sales for 
    // a given month for a particular product (one product per columnn)

    for (i = 0; i < allMonthsOrder.length; i++) {
        month = allMonthsOrder[i];
        html += "<tr>" + "<td>" + month + "</td>";
        // iterate through each product and find if it has data for this month
        for (j = 0; j < allProducts.length; j++) {
            product = allProducts[j];
            html += "<td>";
            if (product.months[month]) {
                html += product.months[month];
            }
            html += "</td>";
        }
        html += "</tr>";
    }
    html += "</table>";
}
嘿看小鸭子会跑 2024-12-07 11:34:49
var snippet = ['<table><thead><tr><th>Name</th><th>Jan-Sales</th><th>Feb-Sales</th><th>Mar-Sales</th></tr></thead><tbody>'];

$('div').each(function()
{
    snippet.push('<tr><td>' + $(this).attr('id') + '</td>');

    $(this).find('span').each(function()
    {
        snippet.push('<td>' + $(this).text() + '</td>');
    });

    snippet.push('</tr>');
});

snippet.push('</tbody></table>');

$('body').html( snippet.join('') );

http://jsfiddle.net/eqfEE/


你可能想知道为什么我使用数组而不是仅仅这样做字符串连接。原因很简单:数组的速度要快得多。

当连接字符串时,JavaScript 会丢弃旧字符串,并创建一个全新的字符串。这会导致创建和销毁过多的对象。

另一方面,当使用 .push() 时,旧数组永远不会被丢弃; JavaScript 只是在数组末尾添加一个新元素...


现在您已经更新了您的问题并澄清了您希望将产品名称作为表标题,您应该执行以下操作:

var productsInfo = {},
    periods = [],
    countProducts = 0,
    countPeriods = 0,
    i,
    snippet = ['<table><thead><tr><th>Period</th>'];

$('div').each(function()
{
    var $this = $(this),
        productName = $this.attr('id'),
        periodsCounted = false;

    productsInfo[productName] = [];

    countPeriods = Math.max($(this).find('span').each(function()
    {
        productsInfo[productName].push( $(this).text() );

        if (!periodsCounted) periods.push( $(this).attr('class') );
    })
    .length, countPeriods);

    periodsCounted = true;
});

for ( var productName in productsInfo )
{
    snippet.push('<th>' + productName + '</th>');
    countProducts++;
}

snippet.push('</tr></thead><tbody>');

for(i = 0; i < countPeriods; i++)
{
    snippet.push('<tr><th>' + periods[i] + '</th>');

    $.each(productsInfo, function(index, e)
    {
        snippet.push('<td>' + e[i] + '</td>');
    });

    snippet.push('</tr>');
}

snippet.push('</tbody></table>');

$('body').html(snippet.join(''));

使用此处的小提琴: http://jsfiddle.net/eqfEE/1/

注意:此代码可以改进。这只是朝着正确方向的一个推动。

var snippet = ['<table><thead><tr><th>Name</th><th>Jan-Sales</th><th>Feb-Sales</th><th>Mar-Sales</th></tr></thead><tbody>'];

$('div').each(function()
{
    snippet.push('<tr><td>' + $(this).attr('id') + '</td>');

    $(this).find('span').each(function()
    {
        snippet.push('<td>' + $(this).text() + '</td>');
    });

    snippet.push('</tr>');
});

snippet.push('</tbody></table>');

$('body').html( snippet.join('') );

http://jsfiddle.net/eqfEE/


You might wonder why I'm using an array instead of just doing string concatenation. The reason is very simple: array's are much faster.

When concatenating strings, JavaScript will discard the old string, and create a brand new one. This leads to too many objects being created and destroyed.

On the other hand, when using .push(), the old array is never discarded; JavaScript merely adds a new element to the end of the array...


Now that you've updated your question and clarified that you want the product names as table headers, you should do the following:

var productsInfo = {},
    periods = [],
    countProducts = 0,
    countPeriods = 0,
    i,
    snippet = ['<table><thead><tr><th>Period</th>'];

$('div').each(function()
{
    var $this = $(this),
        productName = $this.attr('id'),
        periodsCounted = false;

    productsInfo[productName] = [];

    countPeriods = Math.max($(this).find('span').each(function()
    {
        productsInfo[productName].push( $(this).text() );

        if (!periodsCounted) periods.push( $(this).attr('class') );
    })
    .length, countPeriods);

    periodsCounted = true;
});

for ( var productName in productsInfo )
{
    snippet.push('<th>' + productName + '</th>');
    countProducts++;
}

snippet.push('</tr></thead><tbody>');

for(i = 0; i < countPeriods; i++)
{
    snippet.push('<tr><th>' + periods[i] + '</th>');

    $.each(productsInfo, function(index, e)
    {
        snippet.push('<td>' + e[i] + '</td>');
    });

    snippet.push('</tr>');
}

snippet.push('</tbody></table>');

$('body').html(snippet.join(''));

With the fiddle here: http://jsfiddle.net/eqfEE/1/

Note: this code can be improved. This is just a nudge in the right direction.

呆萌少年 2024-12-07 11:34:49

对于完全不同的方式,您可以采用现有的 HTML,并通过简单地指定此 CSS 来显示每个产品的一列:

#coat, #boot, #hat {float: left;}
.Jan-Sales, .Feb-Sales, .Mar-Sales {display: block; margin: 10px;}

这将在每个产品列中从左到右布置产品 div,从上到下布置月份。

你可以在这里看到它: http://jsfiddle.net/jfriend00/V6Dnm/

显然,你可以使用更多 CSS 格式将其格式化为表格(分隔符、适当的间距)。并且,您可以使用 JS 在其上放置列或行标题。

For a completely different take, you can take the existing HTML and display it with a column for each product by simply specifying this CSS:

#coat, #boot, #hat {float: left;}
.Jan-Sales, .Feb-Sales, .Mar-Sales {display: block; margin: 10px;}

This will lay out the product divs left to right and the months top to bottom in each product column.

You can see it here: http://jsfiddle.net/jfriend00/V6Dnm/

Obviously, you could use more CSS formatting to format it as a table (dividers, appropriate spacing). And, you could use JS to put column or row headers on it.

小ぇ时光︴ 2024-12-07 11:34:49

为了进行选择,我最终使用了 2 个循环,如下所示:

 // first loop, get all the "months" from the first div/product
 $("div#coat").each(function(idxMonth) 

 // second loop, get all the products and look for the matching "month"
 $(this).parent().siblings().children('div' + monthClassSelector).each(function(idxSiblingMonth) {

 // where monthClassSelector is something like "Jan2011-Sales" that we got from the 1st loop

To do the selections, I ended up using 2 loops, something like this:

 // first loop, get all the "months" from the first div/product
 $("div#coat").each(function(idxMonth) 

 // second loop, get all the products and look for the matching "month"
 $(this).parent().siblings().children('div' + monthClassSelector).each(function(idxSiblingMonth) {

 // where monthClassSelector is something like "Jan2011-Sales" that we got from the 1st loop
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文