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

本文探讨了HTML元素上同时绑定mouseover/mouseout与click事件,或mouseenter/mouseleave与click事件时,click事件可能无法正常触发的问题。通过两种不同的绑定方式,即已存在元素与未来存在元素的事件绑定,成功解决了事件冲突。

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

针对上述问题,我遇到的有两种情况:

情况一:已经存在的HTML元素绑定事件,可以使用下面这种绑定方式

     $("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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值