1. 程式人生 > >jQuery事件處理(一)

jQuery事件處理(一)

事件處理函式

一.指定事件處理函式

通過下面方法:

jQuery選擇器.事件名(function()){

      <函式體>

});

二.繫結到事件處理函式

1.bind()方法   可以為每一個匹配元素的特定事件(像click)繫結一個事件處理函式。事件處理函式會接收到一個事件物件。

語法:bind(type,[data],fn)

type:事件型別;

data:可選引數,作為event.data屬性值傳遞給事件Event物件的額外資料物件。

fn:繫結到指定事件的事件處理函式。如果fn的函式返回false,則會取消事件的預設行為,並阻止冒泡。

示例:使用bind()方法繫結事件處理函式。

<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery(1).js"></script>
</head>
<body>
<input id="name"/>
<script>
$("input").bind("click",function(){
alert($(this).val());

});
</script>
</body>
</html>

示例:使用bind()方法在事件處理之前傳遞附加的資料。

<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery(1).js"></script>
</head>
<body>
<input id="name"/>
<script>
function handler(event){
  alert(event.data.foo);
}
$("input").bind("click",{foo:"hello"},handler);
</script>
</body>
</html>

  在bind()方法中,使用{foo:"hello" }向事件處理函式傳遞函式。引數名為:foo。引數值為:"hello"。

  在事件處理函式中,可以使用event.data.foo獲得引數值。

示例:使用bind()方法禁止網頁彈出右鍵選單。

<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery(1).js"></script>
<script type="text/javascript">
$(document).ready(function(){
   $(document).bind("contextmenu",function(e){    //contextmenu 滑鼠右鍵
   return false;
});
});
</script>
</head>
<body>
<p>右擊網頁,將不會彈出右鍵選單。</p>

</body>
</html>

 在bind()方法中,指定contextmenu(右擊)事件的處理函式返回false,從而取消事件的預設行為。

2.delegate()方法

  使用delegate()方法將制定元素的特定子元素繫結到指定的事件處理函式。

語法:.delegate(selector,eventType,handler(eventObject))

selector:匹配子元素的選擇器

eventType:事件型別

handler(eventObject):事件處理函式

示例:

<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery(1).js"></script>
<style>
p{
background:yellow;
font-weight:bold;
cursor:pointer;
padding:5px;
}
p.over{
background:#ccc;
}
span{
color:red;
}
</style>
</head>
<body>
<p>Click me</p>

<span> </span>
<script type="text/javascript">
$("body").delegate("p","click",function(){
$(this).after("<p>Another paragraph</p>");
});
</script>
</body>
</html>

注意:delegate()與bind(   )兩個方法的區別。

3.移除事件繫結

unbind()

三.Event物件

示例:Event物件pageX和pageY屬性(滑鼠與文件邊緣的距離)

<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery(1).js"></script>
<style>
div{
color:red;
}
</style>
</head>
<body>
<div id="log"></div>

<script type="text/javascript">
$(document).mousemove(function(e){
$("#log").text("e.pageX:"+e.pageX+",e.pageY:"+e.pageY);
});
</script>
</body>
</html>

示例:type屬性和which屬性:

type:事件型別

which:用於鍵盤事件、滑鼠事件,表示按下的鍵或滑鼠按鈕

<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery(1).js"></script>
<style>
div{
color:red;
}
</style>
</head>
<body>
<input id="whichkey" value=""/>
<div id="log"></div>
<script type="text/javascript">
$("#whichkey").keydown(function(e){
$("#log").html(e.type+":"+e.which);
});
</script>
</body>
</html>

注意:當在input元素中輸入字元時才會在頁面中顯示觸發的事件型別和字元對應的ASCI碼數值。