当前位置: 首页 > 工具软件 > $ click_ > 使用案例 >

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

施辉
2023-12-01

$(选择器).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>

 

 类似资料: