简体   繁体   中英

Confused about adding multiple td's to tr using jQuery

So I have the following code:

<script type="text/javascript">
    $(document).ready(
        function () {
            $("#txt").click(function () {
                var $TableRow = $('<tr></tr>');
                var $TableData = $('<td></td>');
                var $TableData2 = $('<td></td>');

                // Works
                $("#tblControls").append(
                $TableRow.html(
                $TableData.text("Test, Hello World3")
            )
    );

</script>
<div style="display: inline">
    <input type="button" id="txt" value="Add TextBox" style="" />
</div>
<br/>
<table id="tblControls" width="100%">

</table>

But why does this not add two td's to the tr?

$("#tblControls").append(
    $TableRow.html(
        $TableData.text("Test, Hello World3")
        +
        $TableData2.text("Test, Hello World4")
    )
);

What I get is this:

[object Object][object Object]

Because the + operator will result in toString being called on the arguments on either side of it, which yields [object Object] (since $TableData.text("...") and such returns the jQuery object; see text for details).

What you want is:

$TableRow.append($TableData).append($TableData2);

See append in the documentation.

Once the page has been loaded, you need to think much more in terms of objects like elements and such, and less in terms of markup . When you get in the habit of that, it's very powerful.

You are trying to combine two jQuery objects, not two HTML-strings. The .text() method return the jQuery object to support chaining, not the element's HTML as a string.

You can refer to this SO question on how to get the HTML of the entire element, including the actual element.

This is untested, but something like this should do it:

$("#tblControls").append(
        $TableRow.html(
            $("<div />").append($TableData.text("Test, Hello World3")).html() + 
            $("<div />").append($TableData2.text("Test, Hello World4")).html() 
        ) 
);

However, the jQuery documentation says this about what .append() expect:

DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.

Since it can take a jQuery object, you can simply pass $TableData and $TableData2 to the append-method.

$("#tblControls").append(
     $TableRow.append($TableData).append($TableData2);
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM