最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does jQuery's html() method auto-join the argument if it's an array? - Stack Overflow

programmeradmin0浏览0评论

While experimenting, I came across this.

<div id="result"></div>
<script type="text/javascript">
$('#result').html(['<p>This is inside an array</p>', '<em>This is second item in array</em>']);
</script>

When the page was reneded, I could see the following markup in the browser console:

<div id="result">
   <p>This is inside an array</p>
   <em>This is second item in array</em>
</div>

Does this mean that jQuery is running array.join("") in the background if the argument/parameter supplied to the .html() method is an array?

I couldn't find this mentioned in the documentation and hence was curious to know more on this.

While experimenting, I came across this.

<div id="result"></div>
<script type="text/javascript">
$('#result').html(['<p>This is inside an array</p>', '<em>This is second item in array</em>']);
</script>

When the page was reneded, I could see the following markup in the browser console:

<div id="result">
   <p>This is inside an array</p>
   <em>This is second item in array</em>
</div>

Does this mean that jQuery is running array.join("") in the background if the argument/parameter supplied to the .html() method is an array?

I couldn't find this mentioned in the documentation and hence was curious to know more on this.

Share Improve this question asked Mar 28, 2018 at 7:44 asprinasprin 9,83312 gold badges70 silver badges125 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

When passed anything other than a string, .html() empties the element and uses .append() to append the HTML instead, which, when given an array, inserts the HTML strings in the array in the order they appear. This behavior is only documented for .append().

The fact that .html() uses .empty().append() internally when passed an argument that's neither a string nor a function is not stated in its documentation page. The closest is a statement that jQuery empties the element in much the same way when given a function, although that does just follow the same .empty().append() code path.

Note that this does not actually call Array.join() in the way that you would expect. It appends elements represented by each string in the array one by one, rather than joining all the strings first before inserting it via innerHTML. So, for example, the following with a missing (optional) </p> end tag behaves identically — it does not insert a p containing an em child, but a p and an em as siblings, in that order:

$('#result').html(
  [
    '<p>This is inside an array',
    '<em>This is second item in array</em>'
  ]
);

Extending @BoltClock's answer, html method's definition in jquery.js file is as below:

html: function( value ) {
    return access( this, function( value ) {
        var elem = this[ 0 ] || {},
            i = 0,
            l = this.length;

        if ( value === undefined && elem.nodeType === 1 ) {
            return elem.innerHTML;
        }

        // See if we can take a shortcut and just use innerHTML
        if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
            !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

            value = jQuery.htmlPrefilter( value );

            try {
                for ( ; i < l; i++ ) {
                    elem = this[ i ] || {};

                    // Remove element nodes and prevent memory leaks
                    if ( elem.nodeType === 1 ) {
                        jQuery.cleanData( getAll( elem, false ) );
                        elem.innerHTML = value;
                    }
                }

                elem = 0;

            // If using innerHTML throws an exception, use the fallback method
            } catch ( e ) {}
        }

        if ( elem ) {
            this.empty().append( value );
        }
    }, null, value, arguments.length );
},

So this checks for if (typeof value === "string" and when it fails it skips the portion of directly setting the value as innerHTML and if(elem) executes after making sure its an element does what is specified in @BoltClock's answer. i.e.

this.empty().append( value );

and the definition of the empty goes as

// Remove all callbacks from the list
empty: function() {
       if ( list ) {
          list = [];
        }
        return this;
},
发布评论

评论列表(0)

  1. 暂无评论