.replaceWith( newContent )返回: jQuery
描述: 用提供的内容替换集合中所有匹配的元素并且返回被删除元素的集合。
-
添加的版本: 1.2.replaceWith( newContent )
-
newContent用来插入的内容,可能是HTML字符串,DOM元素,或者jQuery对象。
-
-
添加的版本: 1.4.replaceWith( function )
-
function类型: Function()一个函数,返回的内容会替换匹配的元素集合。
-
.replaceWith()
可以从DOM中移除内容,然后在这个地方插入新的内容。请看下面的例子:
1
2
3
4
5
|
|
我们可以用指定的HTML替换第二个 inner <div>
:
1
|
|
结果如下:
1
2
3
4
5
|
|
同样我们也可以一次性替换所有inner<div>
:
1
|
|
结果如下:
1
2
3
4
5
|
|
或者我们可以选择一个元素把它当做替换的内容:
1
|
|
结果如下:
1
2
3
4
|
|
从这个例子可以看出,用来替换的元素从老地方移到新位置,而不是复制。
.replaceWith()
方法,和大部分其他jQuery方法一样,返回jQuery对象,所以可以和其他方法链接使用,
但是需要注意的是: (original
)原始jQuery对象被返回。该对象指向已经从 DOM 中被移除的对象,而不是指向已经取代了它的新元素。
从jQuery 1.4开始 .replaceWith()
都对分离的DOM元素有效。请看下面的例子,.replaceWith()
返回一个jQuery集合子包含一个段落:
1
|
|
.replaceWith()
方法也可以接受一个函数作为它的参数:
1
2
3
|
|
这个结果<div class="container">
被它的三个子元素<div>
替换。函数的返回值可能是一个HTML字符串,DOM元素,或jQuery对象。
其他注意事项:
-
.replaceWith()
方法会删除与节点相关联的所有数据和事件处理程序 。 - 在此之前的jQuery1.9,如果该集合中的第一个节点没有在文档中,
.replaceWith()
将尝试在当前的jQuery集合中添加或更改的节点,在这些情况下返回一个新的jQuery集合,而不是原来的集合。 该方法是否返回一个新的结果,取决于它参数的个数和是否参数节点是否在文档中。 在jQuery1.9中,.after()
,.before()
, 和.replaceWith()
总是返回原始未修改的集合。 尝试在节点上使用这些方法,而不影响父级元素,即,既不是该集合也不是包含他的节点被改变。
例子:
Example: 点击按钮,用包含同样文字的div替换按钮:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
|
Demo:
Example: 用粗体字替换所有段落。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
|
Demo:
Example: On click, replace each paragraph with a div that is already in the DOM and selected with the $()
function. Notice it doesn't clone the object but rather moves it to replace the paragraph.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
|
Demo:
Example: On button click, replace the containing div with its child divs and append the class name of the selected element to the paragraph.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
|