javascript - Warum muss „Parent' vor der Funktion „insertBefore' geschrieben werden, ist aber nicht erforderlich, wenn es auf andere Funktionen angewendet wird?
为情所困
为情所困 2017-05-19 10:24:28
0
1
1007
function insertAfter(newElement,targetElment) {
    var parent = targetElment.parentNode;
    if(parent.lastChild == targetElment) {
        parent.appendChild(newElement); 
    } else {
        parent.insertBefore(newElement,targetElment.nextSibling);
    }
}
为情所困
为情所困

Antworte allen(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 的一些处理。

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage