jquery模拟操作——trigger()函数

在页面中很多效果需要触发才能实现,比如click后的弹窗。但有时我们无法点击或是跳过用户触发,就像网页中那些可恶的广告弹窗

trigger函数可以实现模拟操作。譬如常用的点击动作,我们可以这样,

$('#btn').trigger('click');

这样当页面加载完成后就会立即触发id为btn的点击效果,除此之外还可以触发我们自定义的事件比如

$('#btn').bind('myClick',function(){`````});
$('#btn').trigger('myClick');

利用trigger的特性,我们可以把它变成表单中全选的效果

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title></title>
    </head>

    <body>
        <table border="" cellspacing="" cellpadding="">
            <tr>
                <th>
                    <input type="button" name="" id="" value="全选" /><br />
                    <input type="checkbox" name="" id="" value=""/><label for="">全选</label>
                </th>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" name="" id="" value=""/><label for="">1</label>
                    <input type="checkbox" name="" id="" value=""/><label for="">2</label>
                    <input type="checkbox" name="" id="" value=""/><label for="">3</label>
                </td>
            </tr>
        </table>
        <script src="../jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $('th input[type="button"]').click(function(){
                $('td input').trigger('click');
                
            });
            $('th input[type="checkbox"]').click(function(){
                $('td input').click();
            });
        </script>
    </body>

</html>

 $('td input').click(); 和 $('td input').trigger('click'); 效果是一样的,trigger函数还可以传参,由此我们可以拓展他的各种功能。

原文地址:https://www.cnblogs.com/so-letitgo/p/4443568.html