当一个HTML元素需要添加mouseon、mouseout与click事件,或者mouserenter、mouseleave和click事件时,click事件无法触发

时间:2023-03-08 20:15:03

当一个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>