14-jQuery 插入元素-外部插入

2017-08-31  本文已影响0人  轻思维

jQuery 插入元素-外部插入

作者:曾庆林

以下方法为在指定元素的相邻位置(之前或之后)上插入内容。

after()方法

该方法在匹配元素集合中的每个元素之后插入由参数指定的内容并返回jQuery对象。

before()方法

此方法将参数指定的内容插入到匹配元素集合中的每个元素之前,并返回jQuery对象。

after 案例
html

<button>按钮</button>     
<div class="b">
    <h2>this 我是h2</h2>
</div>

js

$(function(){
    $("button").click(function(){
        $("div").after("<h1>this is H1</h1>");
    })
})

单击完按钮得到的html结构

<button>按钮</button>     
<div class="b">
    <h2>this 我是h2</h2>
</div>
<h1>this is H1</h1>1

before 案例
html

<button>按钮</button>     
<div class="b">
    <h2>this 我是h2</h2>
</div>

js

$(function(){
    $("button").click(function(){
        $("div").before("<h1>this is H1</h1>");
    })
})

单击完按钮得到的html结构

<button>按钮</button>
<h1>this is H1</h1>
<div class="b">
    <h2>this 我是h2</h2>
</div>


insertAfter()方法

该方法在匹配元素集合中的每个元素插入到目标元素之后并返回jQuery对象。

insertBefore()方法

该方法在匹配元素集合中的每个元素插入到目标元素之前并返回jQuery对象。

insertAfter () 案例
html

<button>按钮</button>     
<div class="b">
    <h2>this 我是h2</h2>
</div>

js

$(function(){
    $("button").click(function(){
        $("<h1>this is H1</h1>").insertAfter ($("div"))
    })
})

单击完按钮得到的html结构

<button>按钮</button>
<div class="b">
    <h2>this 我是h2</h2>
</div>
<h1>this is H1</h1>


insertBefore () 案例
html

<button>按钮</button>     
<div class="b">
    <h2>this 我是h2</h2>
</div>

js

$(function(){
    $("button").click(function(){
        $("<h1>this is H1</h1>").insertBefore ($("div"))
    })
})

单击完按钮得到的html结构

<button>按钮</button>
<h1>this is H1</h1>
<div class="b">
    <h2>this 我是h2</h2>
</div>



上一篇下一篇

猜你喜欢

热点阅读