2-1 节点操作
本节编程练习不计算学习进度,请电脑登录imooc.com操作

节点操作

jQuery对节点的操作封装出了一系列的接口,可以接受HTML字符串、DOM 元素、元素数组、或者jQuery对象,用来插在集合中每个匹配元素的不同位置

HTML结构:

$('.inner').after('<p>Test</p>');

$对象:

$('.container').after($('h2'));

回调函数

一个返回HTML字符串、DOM 元素、 或者 jQuery 对象的函数,插在每个匹配元素的后面。接收元素在集合中的索引位置作为参数。在函数中this指向元素集合中的当前元素:

$('p').after(function() {
  return '<div>' + this.className + '</div>';
});

看看其源码的实现,内部都掉了了一个domManip方法

append: function() {
    return this.domManip(arguments, function(elem) {
        if (this.nodeType === 1 
            || this.nodeType === 11 
            || this.nodeType === 9) {
            var target = manipulationTarget(this, elem);
            target.appendChild(elem);
        }
    });
},
prepend: function() {
    return this.domManip(arguments, function(elem) {
        if (this.nodeType === 1 
            || this.nodeType === 11 
            || this.nodeType === 9) {
            var target = manipulationTarget(this, elem);
            target.insertBefore(elem, target.firstChild);
        }
    });
},

.domManip()是jQuery DOM操作的核心函数。dom即Dom元素,Manip是Manipulate的缩写,连在一起就是Dom操作的意思。

对封装的节点操作做了参数上的校正支持,与对应处理的调用:append、prepend、before、after、replaceWith、appendTo、prependTo、insertBefore、insertAfter、replaceAll。

为什么需要用这个domManip函数呢?

我们知道节点操作浏览器提供的接口无非就是那么几个:

appendChild()

通过把一个节点增加到当前节点的childNodes[]组,给文档树增加节点:

cloneNode()

复制当前节点,或者复制当前节点以及它的所有子孙节点:

hasChildNodes()

如果当前节点拥有子节点,则将返回true:

insertBefore()

给文档树插入一个节点,位置在当前节点的指定子节点之前。如果该节点已经存在,则删除之再插入到它的位置:

removeChild()

从文档树中删除并返回指定的子节点:

replaceChild()

从文档树中删除并返回指定的子节点,用另一个节点替换它。

以上接口都有一个特性,传入的是一个节点元素。如果我们传递不是一个dom节点元素,如果是一个字符串,一个函数或者其他呢?

所以针对所有接口的操作,jQuery会抽象出一种参数的处理方案,也就是domManip存在的意义了,针对很多类似接口的参数抽象jQuery内部有很多这样的函数了,如之前属性操作中的jQuery.access。

任务

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
  5. <script src="http://code.jquery.com/jquery-latest.js"></script>
  6. <title>节点操作</title>
  7. </head>
  8. <body>
  9. <div>
  10. </div>
  11.  
  12. <button id="test1">append操作</button>
  13. <button id="test2">after操作</button>
  14. <button id="test3">html操作</button>
  15.  
  16. <h2>Greetings</h2>
  17. <div class="container">
  18. <div class="inner">Hello</div>
  19. <div class="inner">Goodbye</div>
  20. </div>
  21.  
  22. <script type="text/javascript">
  23.  
  24.  
  25. $('#test1').click(function(){
  26. $('.inner').append('<p>Test</p>')
  27. })
  28.  
  29. $('#test2').click(function(){
  30. $('.inner').after('<p>Test</p>');
  31. })
  32.  
  33. $('#test3').click(function(){
  34. alert($('h2').html())
  35. })
  36.  
  37. </script>
  38. </body>
  39. <!-- 1 -->
  40. </html>
  41. <!-- 1 -->
  42. <!-- 1 -->
下一节