JQuery 从 html 表中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16805288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:50:25  来源:igfitidea点击:

JQuery get values from html table

jqueryhtmlarraysobjecthtml-table

提问by Steve Beaty

I am attempting to pull data from a dynamic table using JQuery, but every way I've tried turns the values into something else (the below code will return an "l" instead of the N/A I was expecting. I have tried using .each and .map as the function as well as .val .html and as you can see .text to pull the data. I am stuck as to why and what I am doing wrong. Any help would be greatly appreciated.

我正在尝试使用 JQuery 从动态表中提取数据,但我尝试过的每一种方法都会将值转换为其他值(下面的代码将返回一个“l”而不是 N/AI 所期望的。我尝试使用 .每个和 .map 作为函数以及 .val .html 和你可以看到的 .text 来提取数据。我不知道为什么和我做错了什么。任何帮助将不胜感激。

HTML

HTML

    <table id="attendees" class="attendees">
    <thead>
        <tr style="border-bottom: double;border-color: #007fff" ;="">
            <th>Full Name</th>
            <th>Membership Type</th>
            <th>Membership Expiration Date</th>
            <th>Free Vouchers</th>
            <th>Classes From Pack Remaining</th>
            <th>Yelp Check in</th>
            <th>Payment Option</th>
            <th>Remove</th>
        </tr>
    </thead>
    <tbody>
        <tr class="data">
            <td>Students Name</td>
            <td>N/A</td>
            <td>N/A</td>
            <td>0</td>
            <td>0</td>
            <td>Yes</td>
            <td>
                <ul id="list">
                    <select id="payment" name="payment">
                        <option>Cash/Credit</option>
                        <option>Free Voucher</option>
                        <option>Yelp Check-in</option>
                    </select>
                </ul>
            </td>
            <td>
                <div><a href="#" class="remove"><p>Remove</p></a>
                </div>
            </td>
        </tr>
    </tbody>
</table>

JQuery

查询

$("#submit").live('click', function (e) {
           $("#attendees tr.data").map(function (index, elem) {
               var x = $(this);
               var cells = x.find('td');
               var $data = cells.text();
               //alert($data[1]);
                if ($data[1] == "N/A") {
                alert(true);    
               }

          });
            e.preventDefault();

        });

Final Solution

最终解决方案

Thanks first of all to everyone who chimed in, I honestly learned a little something from each persons answer. In the end this is what I settled on below. In hindsight I probably should of given a more thorough description on what I was attempting to accomplish. Which was to scan multiple rows of data and do something based on the info found in each row. To accomplish this I was forced to separate the trand td.eachfunctions. This allowed me to scan row by row and still get the individual data.
Thanks again for everyone's help especially @TechHunter

首先感谢所有插话的人,老实说,我从每个人的回答中都学到了一些东西。最后,这就是我在下面确定的。事后看来,我可能应该对我试图完成的事情进行更彻底的描述。这是扫描多行数据并根据每行中找到的信息执行某些操作。为了做到这一点,我被迫将trtd.each功能分开。这使我可以逐行扫描并仍然获得单个数据。
再次感谢大家的帮助,尤其是@TechHunter

$("#submit").on('click', function (e) {
    e.preventDefault();

    $("#attendees tbody tr").each(function(i) {
    var $data= [];
    var x = $(this);
    var cells = x.find('td');
    $(cells).each(function(i) {
    var $d= $("option:selected", this).val()||$(this).text();
    $data.push($d);
    });      
        if ($data[1] == "N/A") {
           doSomething(); 
        }
    });
});

采纳答案by TecHunter

Simplest answer would be to add a class when you need to retrieve a value :

最简单的答案是在需要检索值时添加一个类:

HTML

HTML

<table id="attendees" class="attendees">
    <thead>
        <tr style="border-bottom: double;border-color: #007fff" ;="">
            <th>Full Name</th>
            <th>Membership Type</th>
            <th>Membership Expiration Date</th>
            <th>Free Vouchers</th>
            <th>Classes From Pack Remaining</th>
            <th>Yelp Check in</th>
            <th>Payment Option</th>
            <th>Remove</th>
        </tr>
    </thead>
    <tbody>
        <tr class="data">
            <td class="inputValue">Students Name</td>
            <td class="inputValue">N/A</td>
            <td class="inputValue">N/A</td>
            <td class="inputValue">0</td>
            <td class="inputValue">0</td>
            <td class="inputValue">Yes</td>
            <td>
                <ul id="list">
                    <select id="payment" class="inputValue" name="payment">
                        <option>Cash/Credit</option>
                        <option>Free Voucher</option>
                        <option>Yelp Check-in</option>
                    </select>
                </ul>
            </td>
            <td>
                <div><a href="#" class="remove"><p>Remove</p></a>
                </div>
            </td>
        </tr>
    </tbody>
</table>

Javascript

Javascript

$("#submit").on('click', function (e) {
    e.preventDefault();
    var data = $("#attendees tr.data").map(function (index, elem) {
        var ret = [];
        $('.inputValue', this).each(function () {
            var d = $(this).val()||$(this).text();
            ret.push(d);
            console.log(d);
            if (d == "N/A") {
                console.log(true);
            }
        });
        return ret;
    });
    console.log(data);
    console.log(data[0]);
});

It's easier and you only retrieve value you want to retrieve. Fast to implement and to maintain.

它更容易,您只需检索您想要检索的值。快速实施和维护。

Fiddle here

在这里摆弄

回答by qwerty

You should use on()in place of live()(IF your JQuery version supports it)REASON. Just modified your jquery a little bit like this and it worked :

您应该使用on()代替live()(如果您的 JQuery 版本支持)REASON。只是像这样修改了你的 jquery 并且它起作用了

JQuery-

JQuery-

$("#submit").on('click', function (e) {

       $("#attendees tr.data").map(function (index, elem) {
           $(this).find('td').each(function(){
           var $data = $(this).html();
           alert($data);
            if ($data == "N/A") {
            alert(true);    
           }
        });
      });
        e.preventDefault();

    });

UPDATE:-

更新:-

Just check whether there is a selectbox in the td. If it is, then you can get its as shown below :

只需检查td. 如果是,那么你可以得到它,如下所示

if($(this).find("select").length > 0)
     {
         alert("found select")
         alert($(this).find("select").val())
     }

Demo here :-FIDDLE(The updated one showing the value selected in the selectbox)

这里的演示:- FIDDLE(更新的显示在选择框中选择的值)

回答by tymeJV

A couple things, assuming you're using a recent version of jQuery, you're going to want to replace live()with on().

有几件事,假设您使用的是最新版本的 jQuery,您将要替换live()on().

Also, you need to iterate over you cells to find what you're looking for, simply placing it in a variable won't do the trick.

此外,您需要遍历您的单元格以找到您要查找的内容,简单地将它放在一个变量中是行不通的。

$(document).on('click', '#submit' function (e) {
    e.preventDefault();

    //time to iterate over the cells
    $("#attendees tr.data td").each(function(i) {
        if ($(this).text() == "N/A") {
            alert("Found it on cell index: " +i);
        }
    });
});

If you want to use .map()to return an array of the tdtext, you can do:

如果要使用.map()返回td文本数组,可以执行以下操作:

var tdArray = $("#attendees tr.data td").map(function() {
    return $(this).text();
}).get();