【问题标题】:Find td value in table using drop down filtering in jQuery使用 jQuery 中的下拉过滤在表中查找 td 值
【发布时间】:2012-10-27 17:54:42
【问题描述】:

http://medfor.petersenuploads.co.uk/product.php/698/2/clear-ps-honey-jar-with-metal-screw-cap

目前在屏幕中间有一组下拉菜单和一个选项卡(完整产品列表)。如果您单击完整产品列表中的产品之一,它会更新下拉列表。这包括一个隐藏字段(每个案例的项目)

我想要做的是根据 3 个选定的下拉菜单获取每个案例的项目(从表中)的值。例如:

选择 100ml,无菌 R,无标签 - 这与表中的第二行匹配。我想从表中获取“每箱物品”的值,以便我可以设置隐藏的下拉菜单(每箱物品)并获取要添加到购物篮的正确产品。

执行此操作的代码在 script.js 中

// Handles changing any drop downs in the product selection area and updates the choosen item based on label names and field values.
$('.product-options select').change(function() {
    $('p.selection-item').text("");
    $('#selection-name').text($('header>h1').text());
    $('.product-options select').each(function (i) {
        $('p.selection-item').append($("label[for='"+$(this).attr("id")+"']").text() + " " + $('option:selected', this).text(), "<br />");

        var tableRow = $(".product-table td").filter(function() {
            return $(this).text() == "50";
            //Needs to match against all drop down values
        }).closest("tr");
        console.log(tableRow);
    });
    $('div.product-selection h2').removeClass('noshow');
    $('div.product-selection p').removeClass('noshow');
    recalcPrice($('#pid').val());
});

我需要过滤表以获取单行,然后获取倒数第二列的值。我该怎么做?

【问题讨论】:

    标签: jquery html-table filtering


    【解决方案1】:

    假设列/td 放置是静态的,您可以执行以下操作。

    var tableRow = $(".product-table tbody tr").filter(function() {
                var
                    cap = $("#capacity :selected").text(),
                    ster = $("#sterility :selected").text(),
                    lbl = $("#labeltype :selected").text();
                return $(this).find("td").eq(0).text() == cap && $(this).find("td").eq(1).text() == ster && $(this).find("td").eq(2).text() == lbl
            });
    

    如果列/td 放置是动态的,您可以执行以下操作。

    var tableRow = $(".product-table tbody tr").filter(function() {
                var arr = [],
                    cap = $("#capacity :selected").text(),
                    ster = $("#sterility :selected").text(),
                    lbl = $("#labeltype :selected").text();
                $.each($(this).find("td"), function(){
                   arr.push($(this).text());//there was a parenthesis missing here.
                });
                return $.inArray(cap, arr) != -1 && $.inArray(ster, arr) != -1 && $.inArray(lbl, arr) != -1;
            });
    

    【讨论】:

    • 第一段代码有效,但第二段无效。不明白为什么 - 不会引发错误。当我返回 时,如何从行中获取第 4 个 ?我见过有点像 $(tableRow, tr) 的代码,但在任何地方都找不到对它的引用。感谢您迄今为止的帮助!
    • 第二个选项中缺少括号。请再次检查该代码。
    • 要在tr 中获取第4 个td,可以使用tableRow.find("td:nth-child(4)")tableRow.find("td").eq(3).eq() 从零开始)。
    • 好的。动态版本现在可以工作,但是当我尝试抓取 tableRow.find("td").eq(3).text();是空的吗?
    • 您是否尝试console.log(tableRow) 来查看选择了什么?如果选择了一个元素,则执行console.log(tableRow).find("td").eq(3) 以查看选择了什么。让我知道你发现了什么(或者如果你发现了什么)。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签