Usage of jquery map function for table

2019-05-24 05:03发布

问题:

I have this table:

    <table id="tblNyttUtstyr">
        <thead>
            <tr>
                <th data-field="UtlevertUtstyrID">UtstyrsID</th>
                <th data-field="UtstyrNavn">Navn</th>
                <th data-field="Utlevert">Utlevert</th>
                <th data-field="Comment">Kommentar</th>
            </tr>
        </thead>
<tbody>
<tr>
   <td>1</td>
   <td>Motorola defy+</td>
   <td>true</td>
</tr>
<tr>
   <td>3</td>
   <td>Samsung SII</td>
   <td>true</td>
</tr>
</tbody>
</table>

Then I have this script

var test = $("#tblNyttUtstyr tbody tr").map(function () {
            var $row = $(this);

            return {
                UtlevertUtstyrID: $row.find(":nth-child(1)").text(),
                Comment: $row.find(":nth-child(2)").text()
            };
        }).get();

        $("#console").text("content: " + test);

The return value are like this: "content: [object],[object]"

Anyone know howto get the values, the text instead of just object

Thanks

回答1:

.map returns a jQuery object.

You need to use callbacks.

    function setConsole(obj) {
        $("#console").text("content: " + obj.Comment);
    }

    var test = $("#tblNyttUtstyr tbody tr").map(function () {
        var $row = $(this);

        setConsole( {
            UtlevertUtstyrID: $row.find(":nth-child(1)").text(),
            Comment: $row.find(":nth-child(2)").text()
        } );

    }).get();

Update: change the setConsole function to this:

function setConsole(obj) {
    var c = $("#console");
    c.text(c.text() + "content: " + obj.Comment);
}

Or else every new object will just be overwritten.

See my demo here: http://jsfiddle.net/maniator/FrURX/