當一個HTML元素需要添加mouseon、mouseout與click事件,或者mouserenter、mouseleave和click事件時,click事件無法觸發
針對上述問題,我遇到的有兩種情況:
情況一:已經存在的HTML元素綁定事件,可以使用下面這種綁定方式
$("button").mouseon(function(){
$("p").text("滑入");
}).click(function(){
$("p").text("點擊");
});
或者:
$("button").mouseout(function(){
$("p").text("滑出");
}).click(function(){
$("p").text("點擊");
});
或者:
$("button").hover(function(){
$("p").text("滑過");
}).click(function(){
$("p").text("點擊");
});
情況二:未來存在的要素綁定事件,可以使用下面這種綁定方式
$("button").live("hover click",function(event){
$("span").text(event.type);
if(event.type=="mouseenter"){
$("p").text("滑進");
}
if(event.type=="mouseleave"){
$("p").text("滑出");
}
if(event.type=="click"){
$("p").text("點擊");
}
});
下面是完整的測試代碼:
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").live("hover click",function(event){ $("span").text(event.type); if(event.type=="mouseenter"){ $("p").text("滑進"); } if(event.type=="mouseleave"){ $("p").text("滑出"); } if(event.type=="click"){ $("p").text("點擊"); } }); }); </script> </head> <body> <p>這是一個段落。</p> <span>顯示觸發的事件。</span> <button>請點擊這里</button> </body> </html>
