为什么insertBefore函数前面还得写上parent,应用到其他函数里就不用了

function insertAfter(newElement,targetElment) {
    var parent = targetElment.parentNode;
    if(parent.lastChild == targetElment) {
        parent.appendChild(newElement); 
    } else {
        parent.insertBefore(newElement,targetElment.nextSibling);
    }
}
回复
阅读 3.3k
1 个回答

因为 DOM 的 Node 没有这个方法啊,你想这么用的话就把方法植入到 Node 的原型上

Node.prototype.insertAfter = function insertAfter(newNode, targetNode) {
  if (!(this instanceof Node)) {
    throw new TypeError('Illegal invocation')
  }
  
  if (arguments.length < 2) {
    throw new TypeError("Failed to execute 'insertAfter' on 'Node': 2 arguments required, but only " + arguments.length +" present.")
  }
  
  if (!(newNode instanceof Node)) {
    throw new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 1 is not of type 'Node'.")
  }
  
  if (targetNode !== null && !(targetNode instanceof Node)) {
    throw new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 2 is not of type 'Node'.")
  }
  
  if (targetNode !== null && targetNode.parentNode !== this) {
    throw new DOMException("Failed to execute 'insertAfter' on 'Node': The node before which the new node is to be inserted is not a child of this node.")
  }

  if(!targetNode || this.lastChild == targetNode) {
    this.appendChild(newNode); 
  } else {
    this.insertBefore(newNode, targetNode.nextSibling);
  }
}

这样就可以用 parent.insertAfter(newElement, targetElment),这里模仿了 insertBefore 的一些处理。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏