一、after()和before()方法的区别
after()——其方法是将方法里面的参数添加到jquery对象后面去;
如:A.after(B)的意思是将B放到A后面去;
before()——其方法是将方法里面的参数添加到jquery对象前面去。
如:A.before(B)的意思是将A放到B前面去;
二、insertAfter()和insertBefore()的方法的区别
其实是将元素对调位置;
可以是页面上已有元素;也可以是动态添加进来的元素。
如:A.insertAfter(B);即将A元素调换到B元素后面;
如CC
HELLO
使用$("span").insertAfter($("p"))后,就变为HELLO
CC了。两者位置调换了三、append()和appendTo()方法的区别
append()——其方法是将方法里面的参数添加到jquery对象中来;
如:A.append(B)的意思是将B放到A中来,后面追加,A的子元素的最后一个位置;
appendTo()——其方法是将jquery对象添加到appendTo指定的参数中去。
如:A.appendTo(B)的意思是将A放到B中去,后面追加,B的子元素的最后一个位置;
四、prepend()和prependTo()方法的区别
append()——其方法是将方法里面的参数添加到jquery对象中来;
如:A.append(B)的意思是将B放到A中来,插入到A的子元素的第一个位置;
appendTo()——其方法是将jquery对象添加到appendTo指定的参数中去。
如:A.appendTo(B)的意思是将A放到B中去,插入到B的子元素的第一个位置;
例子
1、insert局部方法
function _insert(parent, position, any, index) {
if ($.isFunction(any)) {
any = any.call(parent);
}
// 字符串
if ($.isString(any)) {
if (regTag.test(any)) {
parent.insertAdjacentHTML(position, any);
} else {
parent.insertAdjacentText(position, any);
}
}
// 数字
else if ($.isNumber(any)) {
parent.insertAdjacentText(position, any);
}
// 元素
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 = {
append: function(any) {
return this.each(function(index) {
_insert(this, 'beforeend', any, index);
});
},
prepend: function(any) {
return this.each(function(index) {
_insert(this, 'afterbegin', any, index);
});
},
before: function(any) {
return this.each(function(index) {
_insert(this, 'beforebegin', any, index);
});
},
after: function(any) {
return this.each(function(index) {
_insert(this, 'afterend', any, index);
});
}
};
3、prependTo、prependTo、insertBefore、insertAfter
这些带后缀的与上面的不同的是,返回的结果不一样。如:
$('#demo').append('');
// => 返回的是 $('#demo')
$('').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() 方法在被选元素之前插入内容。
- 第一个li标签
效果图
html结构图



