jQuery prepend( ) 方法

使用jQuery的 append( ) 方法,我们可以在被选元素的结尾处插入指定的内容。

语法格式:

$(selector).prepend(content,function(index,currentHTML))

参数:

content(必需):插入的内容(可以是HTML元素)。

function(index,currentHTML)(可选):返回待插入内容的函数。

注意:

(1)index为元素的索引。

(2)currentHTML为被选元素的当前 HTML。

示例:

(1)常规方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="../jQuery/jQuery.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("div").prepend("<p class = 'para'>一段文字。</p>");
            })
        })
    </script>
    <style>
        div {
            width: 150px;
            height: 150px;
            background-color: rgba(74, 165, 66, 0.404);
        }
        .para {
            color: blue;
        }
    </style>
</head>
<body>
    <button>按钮</button>
    <div><p>我是一个盒子。</p></div>
</body>
</html>

 

点击按钮,DIV的开头处将插入新段落,效果如图:

(2)函数方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="../jQuery/jQuery.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("ol li").prepend(function(index,currentHTML){
                    return "<em>我的索引号为 " + index + " 我当前的HTML为" + currentHTML + "</em>";
                })
            })
        })
    </script>
</head>
<body>
    <ol>
        <li><b>我是列表项1。</b></li>
        <li><b>我是列表项2。</b></li>
        <li><b>我是列表项3。</b></li>
    </ol>
    <button>按钮</button>
</body>
</html>

点击按钮,效果如图:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值