當一個HTML元素需要添加mouseon、mouseout與click事件,或者mouserenter、mouseleave和click事件時,click事件無法觸發


當一個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>

 

    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM