本文實例講述了jQuery中trigger()方法用法。分享給大家供大家參考。具體分析如下:
此方法觸發匹配元素指定類型的事件。
語法結構一:
規定匹配元素被觸發的事件類型。
$(selector).trigger(event,param1,param2,...)
參數列表:
參數 | 描述 |
event | 規定指定元素要觸發的事件。 可以是自定義事件(使用 bind() 函數來附加),或者任何標準事件。 |
param | 可選。傳遞到事件處理程序的額外參數。 額外的參數對自定義事件特別有用。 |
實例代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.49028c.com/" />
<title>trigger()函數-武林網</title>
<style type="text/css">
div{
width:200px;
height:200px;
border:1px solid blue;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").click(function(){
$("div").append("添加的內容");
});
$("button").click(function(){
$("div").trigger("click");
})
})
</script>
</head>
<body>
<div></div>
<button>點擊激活事件</button>
</body>
</html>
當點擊button按鈕可以的時候可以出發div上的click事件,進而執行click事件處理函數。
語法結構二:
以事件對象作為參數規定匹配元素要被觸發的事件類型。
$(selector).trigger(eventObj)
參數列表:
參數 | 描述 |
eventObj | 事件對象規定了事件發生時運行的函數。 |
實例代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.49028c.com/" />
<title>trigger()函數-武林網</title>
<style type="text/css">
div{
width:200px;
height:200px;
border:1px solid blue;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").click(function(){
$("div").append("添加的內容");
});
var e=jQuery.Event("click");
$("button").click(function(){
$("div").trigger(e);
})
})
</script>
</head>
<body>
<div></div>
<button>點擊激活事件</button>
</body>
</html>
希望本文所述對大家的jQuery程序設計有所幫助。