假设我有一个空的div:

<div id='myDiv'></div>

是这样的:

$('#myDiv').html("<div id='mySecondDiv'></div>");

同为:

var mySecondDiv=$("<div id='mySecondDiv'></div>");
$('#myDiv').append(mySecondDiv);

当前回答

除了给出的答案,在这种情况下,你有这样的东西:

<div id="test">
    <input type="file" name="file0" onchange="changed()">
</div>
<script type="text/javascript">
    var isAllowed = true;
    function changed()
    {
        if (isAllowed)
        {
            var tmpHTML = $('#test').html();
            tmpHTML += "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
            $('#test').html(tmpHTML);
            isAllowed = false;
        }
    }
</script>

这意味着如果上传了任何文件,您想要自动添加一个文件上传,上述代码将不起作用,因为在文件上传后,第一个文件上传元素将被重新创建,因此上传的文件将从其中删除。你应该使用.append()来代替:

    function changed()
    {
        if (isAllowed)
        {
            var tmpHTML = "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
            $('#test').append(tmpHTML);
            isAllowed = false;
        }
    }

其他回答

如果你的.add是指.append,那么如果#myDiv是空的,结果也是一样的。

表演一样吗?不知道。

.html(x)最终会做与.empty().append(x)相同的事情

你可以用第二种方法来达到同样的效果:

var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);

Luca提到html()只是插入html,这导致了更快的性能。

在某些情况下,你会选择第二种方法,考虑:

// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");

// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);

除了给出的答案,在这种情况下,你有这样的东西:

<div id="test">
    <input type="file" name="file0" onchange="changed()">
</div>
<script type="text/javascript">
    var isAllowed = true;
    function changed()
    {
        if (isAllowed)
        {
            var tmpHTML = $('#test').html();
            tmpHTML += "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
            $('#test').html(tmpHTML);
            isAllowed = false;
        }
    }
</script>

这意味着如果上传了任何文件,您想要自动添加一个文件上传,上述代码将不起作用,因为在文件上传后,第一个文件上传元素将被重新创建,因此上传的文件将从其中删除。你应该使用.append()来代替:

    function changed()
    {
        if (isAllowed)
        {
            var tmpHTML = "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
            $('#test').append(tmpHTML);
            isAllowed = false;
        }
    }

嗯,.html()使用. innerhtml,这比DOM创建更快。

.html()将替换所有内容。

.append()只会在结尾追加。