在頁面中很多效果需要觸發才能實現,比如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函數還可以傳參,由此我們可以拓展他的各種功能。
