2

I have a table that looks something like this, where most of the rows are not displayed:

<table id="myTable" class="tablesorter">
    <thead>
        <tr>
            <th>header1</th>
            <th>header2</th>
            ...
        </tr>
    </thead>
    <tbody>
        <tr style="display:none;">
            <td>content1</td>
            <td>content2</td>
            ...
        </tr>
        <tr style="display:none;">
            <td>content1</td>
            <td>content2</td>
            ...
        </tr>
        <tr>
            <td>content1</td>
            <td>content2</td>
            ...
        </tr>
        ...
    </tbody>
</table>

I am trying to access all of the visible rows in the table, and concatenate each cells' value to a string that will be output into CSV. I have some jQuery code but it doesn't get very far at the moment:

<input type="button" value="Export" id="csv-export" />

<script type="text/javascript">
    $(function () {
        $("#csv-export").click(function () {
            var csvStr = "";
            $("#myTable tr:visible td").each(function () {   //for each td in each visible row
                if ($(this).has("a") == false) {   //if the td does not contain a link
                    csvStr += $(this).html();   //Append the td's html
                }
            });
            $.get('@Url.Action("CSVExport")', { csv: csvStr });
        });
    });
</script>

The line $("#myTable tr:visible td").each(function () { is failing. Any help here? I'm a bit of an amateur at writing this type of code. I want this code to select all tr elements that are not set to display: none and then for each of these, select and access all td elements.

4

2 回答 2

1

jsFiddle Demo

您遇到的问题是jQuery API将返回一个集合。为了从中获得真实值,您应该检查长度属性。

if (!$(this).has("a").length) {  
 csvStr += $(this).html();
}

否则,其他一切都可以正常工作。

于 2013-09-16T23:31:10.857 回答
1

.has()方法返回一个 jQuery 对象,一个对象是 JavaScript 中的一个真值,has不像hasClass方法不返回一个布尔值,它是一个过滤方法,你应该使用length属性来代替:

if (!$(this).find("a").length) { 

如果要排除td具有后代的元素,a可以使用.not()方法:

$("#myTable tr:visible td").not(":has(a)").each(function () {

如果要创建逗号分隔值字符串,可以使用.map()方法:

var csvString = $("#myTable tr:visible td").not(":has(a)").map(function() {
     return $.trim( $(this).text() );
}).get().join();
于 2013-09-16T23:28:32.497 回答