jQuery的html()方法是否自动加入参数,如果它是一个数组?

时间:2018-03-28 07:44:15

标签: javascript jquery

在尝试时,我遇到了这个。

<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>

当页面被重新加入时,我可以在浏览器控制台中看到以下标记:

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

如果提供给。array.join("")方法的参数/参数是数组,这是否意味着jQuery在后台运行html()

我无法在文档中找到这一点,因此很想知道更多相关内容。

2 个答案:

答案 0 :(得分:12)

当传递除字符串以外的任何内容时,.html()清空该元素并使用.append()来替换HTML,当给定数组时,按照它们的顺序在数组中插入HTML字符串出现。仅对.append()记录此行为。

.html()在传递既不是字符串也不是函数的参数时内部使用.empty().append()的事实未在其文档页面中说明。最接近的是jQuery以与when given a function大致相同的方式清空元素的语句,尽管它只遵循相同的.empty().append()代码路径。

请注意,这实际上并没有按照您期望的方式调用Array.join()。它逐个追加数组中每个字符串表示的元素,而不是在通过innerHTML插入之前先连接所有字符串。因此,例如,以下缺少(可选)</p>结束标记的行为相同 - 它不会插入包含p子项的em,而是pem一个$('#result').html( [ '<p>This is inside an array', '<em>This is second item in array</em>' ] ); 作为兄弟姐妹,按顺序:

<dict>
    <key>ProgramArguments</key>
    <array>
        <string>/Applications/ExD2017/render/bin/renderqueue</string>
        <string>-h</string>
        <string>127.0.0.1</string>
    </array>
</dict>

答案 1 :(得分:2)

扩展@ BoltClock的答案,html方法在jquery.js文件中的定义如下:

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 );
},

因此,这会检查if (typeof value === "string",当它失败时,它会跳过直接将值设置为innerHTML的部分,并在确保其if(elem)执行的操作后执行element在@ BoltClock的答案中指定。即。

this.empty().append( value );

并且empty的定义为

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