jQuery追加嵌套

时间:2013-01-15 08:28:46

标签: jquery append

var f = a('<span class="customSelectInnerText" />');
var e = a('<span class="customSelect"><span class="customSelectInner"></span></span>').append(f);

结果:

<span class="customSelect>
   <span class="customSelectInner"></span>
   <span class="customSelectInnerText">Text</span>
</span>

而不是所需的:

<span class="customSelect>
   <span class="customSelectInner">
      <span class="customSelectInnerText">Text</span>
   </span>
</span>

3 个答案:

答案 0 :(得分:2)

如果您只想调整代码,则需要将f附加到. customSelectInner,可以使用find完成。

var f = a('<span class="customSelectInnerText" />');
var e = a('<span class="customSelect">' +
          '<span class="customSelectInner"></span></span>')
         .find('.customSelectInner')append(f);

请注意,我会破坏该代码,因此每个元素都有自己的变量,它更易读,更易于维护和调试。

答案 1 :(得分:1)

您的语句选择最外层的元素。您必须在追加上一个<span>之前选择内部子项。改为:

var e = a('<span class="customSelect"><span class="customSelectInner"></span></span>')
            .children().append(f);

答案 2 :(得分:1)

var f = a('<span class="customSelectInnerText" />');

var e = a('<span class="customSelect"><span class="customSelectInner"></span></span>');
$(".customSelectInner").append(f);