Jquery学习之DOM操作

1.追加

 .insertBefore()在现有元素外部、之前添加内容;
.prependTo()在现有元素内部、之前添加内容;
.appendTo()在现有元素内部、之后添加内容;
.insertAfter()在现有元素外部、之后添加内容。

$(document).ready(function() {
  $('<a href="#top">back to top</a>').insertAfter('div.chapter p');
  $('<a id="top"></a>').prependTo('body');
});

 2.包裹

 .wrapAll()把所有脚注都包含;

 .wrap()将每一个脚注分别包装。

$(document).ready(function() {
    $('span.footnote')
    .insertBefore('#footer')
    .wrapAll('<ol id="notes"></ol>')
    .wrap('<li></li>');
});

3.迭代

 .each():这个方法接受一个回调函数,这个函数会针对匹配的元素集中的每个元素都调用一次 。

$(document).ready(function() {
    var $notes = $('<ol id="notes"></ol>').insertBefore('#footer');
    $('span.footnote').each(function(index) {
        $('<sup>' + (index + 1) + '</sup>').insertBefore(this);
        $(this).appendTo($notes).wrap('<li></li>');
    });
});

 4.反向

 .before和insertBefore;

 .append和appendTo;

 $('<p>Hello</p>').appendTo('#container'); 
$('#container').append('<p>Hello</p>');  

5.串联

 .join('')

$(document).ready(function () {
  var $notes = $('<ol id="notes"></ol>')
    .insertBefore('#footer');
  $('span.footnote').each(function (index) {
    $(this)
      .before([
        '<a href="#footnote-',
        index + 1,
        '" id="context-',
        index + 1,
        '" class="context">',
        '<sup>',
        index + 1,
        '</sup></a>'
      ].join(''))
      .appendTo($notes)
      .append([
        '&nbsp;(<a href="#context-',
        index + 1,
        '">context</a>)'
      ].join(''))
      .wrap('<li id="footnote-' + (index + 1) + '"></li>');
  });
});

 

 6.复制

 .clone() 

  在默认情况下, .clone()方法不会复制匹配的元素或其后代元素中绑定的事件。不过,可以为这个方法传递一个布尔值参数,将这个参数设置为true,就可以连同事件一起复制,即.clone(true) 。

$('div.chapter p:eq(0)').clone().insertBefore('div.chapter');

 

7.setter getter

 .html()

 .text()

$(document).ready(function () {
  $('span.pull-quote').each(function (index) {
    var $parentParagraph = $(this).parent('p');
    $parentParagraph.css('position', 'relative');
    var $clonedCopy = $(this).clone();
    $clonedCopy
      .addClass('pulled')
      .find('span.drop').html('&hellip;').end()//drop类文本改为省略号...
      .text($clonedCopy.text())//获取纯文本,原文本的效果会移除,如加粗等
      .prependTo($parentParagraph);
  });
});

 

总结:

(1) 要在HTML中创建新元素,使用$()函数。
(2) 要在每个匹配的元素中插入新元素,使用:
   .append()
   .appendTo()
   .prepend()
   .prependTo()
(3) 要在每个匹配的元素相邻的位置上插入新元素,使用:
   .after()
   .insertAfter()
   .before()
   .insertBefore()
(4) 要在每个匹配的元素外部插入新元素,使用:
   .wrap()
   .wrapAll()
   .wrapInner()
(5) 要用新元素或文本替换每个匹配的元素,使用:
   .html()
   .text()
   .replaceAll()
   .replaceWith()
(6) 要移除每个匹配的元素中的元素,使用:
   .empty()
(7) 要从文档中移除每个匹配的元素及其后代元素,但不实际删除它们,使用:
   .remove()
   .detach()

posted @ 2017-09-02 17:04  pding  阅读(275)  评论(0编辑  收藏  举报