Rumah > Soal Jawab > teks badan
function insertAfter(newElement,targetElment) {
var parent = targetElment.parentNode;
if(parent.lastChild == targetElment) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement,targetElment.nextSibling);
}
}
習慣沉默2017-05-19 10:26:28
Oleh kerana DOM Node tidak mempunyai kaedah ini, jika anda ingin menggunakannya dengan cara ini, hanya tanamkan kaedah tersebut ke dalam prototaip 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);
}
}
Dengan cara ini anda boleh menggunakan beberapa pemprosesan parent.insertAfter(newElement, targetElment)
,这里模仿了 insertBefore
.