jquery 追加元素append、prepend、before、after用法与区别分析

2020-05-24 21:33:29易采站长站整理

else if ($.isElement(any)) {
parent.insertAdjacentElement(position, index > 0 ? any.cloneNode(!0) : any);
}
// Yquery
else if (_isYquery(any)) {
any.each(function() {
_insert(parent, position, this);
});
}
}

2、append、prepend、before、after


$.fn = {
/**
* 追插
* 将元素后插到当前元素(集合)内
* @param {String/Element/Function} any
* @return this
* @version 1.0
* 2013年12月29日1:44:15
*/
append: function(any) {
return this.each(function(index) {
_insert(this, 'beforeend', any, index);
});
},
/**
* 补插
* 将元素前插到当前元素(集合)内
* @param {String/Element/Function} any
* @return this
* @version 1.0
* 2013年12月29日1:44:15
*/
prepend: function(any) {
return this.each(function(index) {
_insert(this, 'afterbegin', any, index);
});
},
/**
* 前插
* 将元素前插到当前元素(集合)前
* @param {String/Element/Function} any
* @return this
* @version 1.0
* 2013年12月29日1:44:15
*/
before: function(any) {
return this.each(function(index) {
_insert(this, 'beforebegin', any, index);
});
},
/**
* 后插
* 将元素后插到当前元素(集合)后
* @param {String/Element/Function} any
* @return this
* @version 1.0
* 2013年12月29日1:44:15
*/
after: function(any) {
return this.each(function(index) {
_insert(this, 'afterend', any, index);
});
}
};

3、prependTo、prependTo、insertBefore、insertAfter
这些带后缀的与上面的不同的是,返回的结果不一样。如:


$('#demo').append('<a/>');
// => 返回的是 $('#demo')
$('<a/>').appendTo($('#demo'));
// => 返回的是$('a');

因此两者的关系只是返回结果不一样,其他的都一样,可以这么解决:


_each({
appendTo: 'append',
prependTo: 'prepend',
insertBefore: 'before',
insertAfter: 'after'
}, function(key, val) {
$.fn[key] = function(selector) {
this.each(function() {
$(selector)[val](this);
});
return this;
};
});

jquery 追加元素的方法(append prepend after before 的区别)

append() 方法在被选元素的结尾插入内容。

prepend() 方法在被选元素的开头插入内容。

after() 方法在被选元素之后插入内容。

before() 方法在被选元素之前插入内容。