2

我玩了一点 jQuery,我有了一个想法,所以我决定试一试。

$('table').append('<thead><tr><th><th><th>');

可以想象,这产生了:

table
-thead
--tr
---th
---th
---th

我知道您可以编写以下 HTML 并获得与上述等效的结构:

<table>
  <thead>
    <tr>
      <th>
      <th>
      <th>

我试图查看 jQuery 源 [1],似乎没有任何迹象表明 jQuery 做了任何与htmlString. jQuery 是否只是将 htmlString 附加为普通字符串并让浏览器完成工作,还是我遗漏了什么?

如果是浏览器完成工作,这是否意味着我可以预期不同浏览器之间的不同行为?

[1] https://github.com/jquery/jquery/blob/0600a29256be76bd87adb547545bf7219fafb6ee/src/manipulation.js#L41

4

1 回答 1

5

Does jQuery simply append the htmlString as a normal string and let the browser do the work, or is there something I'm missing?

Yes, and yes. :-)

jQuery lets the browser do the work, but it does some things to help with situations that might otherwise be problematic. For instance:

var row = $("<tr><td>foo</td></tr>");

You can do that in jQuery, and you get back a jQuery object wrapping a row that isn't (yet) in the DOM, which has a cell in it.

Which seems simple enough, but jQuery has to do work to ensure that that HTML string is parsed within the context of a table (because if you try to make the browser parse it within, say, a div, there's a problem).

Edit: Rob W pointed to some relevant source for this:

// We have to close these tags to support XHTML (#13200)
wrapMap = {

    // Support: IE 9
    option: [ 1, "<select multiple='multiple'>", "</select>" ],

    thead: [ 1, "<table>", "</table>" ],
    col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
    tr: [ 2, "<table><tbody>", "</tbody></table>" ],
    td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

    _default: [ 0, "", "" ]
};

Code in jQuery's internal buildFragment function uses the map above (and objects derived from it) to ensure the HTML is parsed correctly.

于 2013-07-21T10:51:57.300 回答