使用jQuery附加DOM元素的这两种方法有什么不同?

时间:2012-08-10 22:31:52

标签: javascript jquery google-chrome google-chrome-extension

我遇到了以下两段代码的不同结果。不过,我想,他们应该表现得相同。任何人都可以告诉我这些差异,以及我何时应该使用其中一个?

function ContentHeader(selector){
    "use strict";
    var contentHeader = $(selector);

    var headerTitle = $('<span/>', {
        'class': 'headerTitle'
    }).appendTo(contentHeader);

    //OPTION A: This is my preferred method, but, after calling appendTo, no DOM element is added to the DOM tree.
    var headerTitleInput = $('<input/>', {
        'class': 'headerInput',
        type: 'text'
    }).appendTo(headerTitle);

    //OPTION B: By contrast, this method is less robust / just a string, but the DOM element is added correctly to the DOM tree.
    headerTitle.append('<input type="text" class="headerInput" />');
}

我更喜欢使用jQuery的DOM对象构造函数,因为它整齐地封装了属性,但显然我并不完全理解它。

编辑:我正在为这个问题生成一个jsFiddle。请回来查看。

1 个答案:

答案 0 :(得分:0)

我相信我找到了答案。不幸的是,它没有任何性感或教育。

当我创建ContentHeader对象时,我返回一些公共方法。其中一个叫做'SetTitle'。它看起来像这样:

setTitle: function(title){
  headerTitle.text(title);
}

此方法在异步代码执行块期间与服务器进行交互。似乎创建一个jQuery对象的开销是根据时间产生不同的,尴尬的结果。这个问题在jsFiddle中无法重现。