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函數還可以傳參,由此我們可以拓展他的各種功能。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM