JQuery为每个跨度追加子节点

时间:2015-08-14 12:36:34

标签: jquery

我有以下HTML代码:

<div class="truc">
    <span class="test" date-url="12.mp3"></span>
</div>
<div class="truc">
    <span class="test" date-url="64.mp3"></span>
<div>

我想在span中添加一个音频标签,其中src属性是span标签的data-url属性。 我写了以下代码:

$('span.test').each(function(){
    var ajout = '<audio><source src="'+$(this).attr("data-url")+'"></audio>';
    $(this).append(ajout);
});

它有效,但没有优化,因为追加是在每个&#39;内。环。我正在努力寻找更好的写作方式。也许你可以帮助我?非常感谢。

1 个答案:

答案 0 :(得分:3)

我建议如下:

// create a single instance of the element(s) you
// wish to append:
var newHTML = $('<audio />', {
    'html' : '<source></source'
}),
// create an unitialised variable to use within 
// within the (inevitable) loop:
    clone;

// select the element(s) to which you wish
// to append new content:
$('span.test').append(function() {

  // create a reference to the cloned element
  // (to avoid recreating the same element(s)
  // every iteration):
  clone = newHTML.clone(true);

  // find the <audio> element within the
  // cloned element, and update its 'src'
  // property; within this loop 'this'
  // refers to the current span.test element
  // over which we're iterating:
  clone.find('audio').prop('src', this.dataset.url);

  // return the cloned, and updated, elements to
  // the append method:
  return clone;
});

参考文献: