$().click()和$().on('click','要选择的元素',function(){})的区别

$(选择器).click(function(){}):页面中已经存在的DOM。

$(ducument).on(‘click’,‘要选择的元素’,function(){}):动态创建的元素也能触发事件,
且ducument在页面已经存在,而不是动态添加的。

on方法包含很多事件,点击,双击等等事件。

下面举例子说明:

//CSS可忽略
<!doctype html>
<html>
<head>
    <style>
    ul{
        list-style: none;
        display: flex;    
    }
    ul li{
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        background: pink;
        font-weight: bold;
        border: 1px solid #eee;
    }
    ul li:hover{
        cursor: pointer;
    }
</style>
</head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<body>
    <div>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
    </div>
</body>
<script>
    /* 
     $('li').click(function(){
             alert($(this).text())
     })
     $('ul').append('<li>6</li>')
    */

     
    //上面这段js运行后,第6个li添加了进去,但是没有click点击事件
    
    //----------- 分割线 --------------
    //ul是已经存在的
    $('ul').on('click','li',function(){//这里改为用on()方法,第6个li也有了点击事件
        alert($(this).text())          
    })
    $('ul').append('<li>6</li>')
</script>
</body>
</html>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值