jq 事件

jq 事件

  • jq事件
  • jq中的事件操作,都是基於js的addEventListener語法
  • 特點:
    1.一個元素的多個事件,都會執行,不會覆蓋
    2.支持多個事件添加
    3.支持事件委託
    4.事件的命名空間
 <div id="div1" style="width: 100px;height: 100px;background:black;margin:0 auto;"></div>
    <div id="div2" style="width: 100px;height: 100px;background:black;margin:10px auto;"></div>
    <div id="div3" style="width: 100px;height: 100px;background:black;margin:10px auto;"></div>
     
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
    //jq 事件
    //jq中的事件操作,都是基於js的addEventListener語法

    //特點 1.一個元素的多個事件,都會執行,不會覆蓋
     $('#div1').on('click',function(){
         alert(111);
     })
     $('#div1').on('click',function(){
         alert(222);
     })
     $('#div1').on('click',function(){
         alert(333);
     })

    //2.支持多個事件添加
    //on('click mouseover',function(){})
    $('#div2').on('click mouseover',function(){
        console.log(789);
    })
    //多個事件還可以寫成對象的方式
    $('#div3').on({
        click:function(){console.log(111)},
        mouseover:function(){console.log(222)}
    })
    
    //3.支持事件委託

    $('ul').on('click','li',function(){
      $(this).css('background','red').siblings().css('background','') //this 指向的是被點擊的元素,與js的evt.target相同
    })
    //4.事件的命名空間
    //mouseover.hello 就叫做事件的命名空間, 可以隨便定義
    //用途:方便在同一元素上同時綁定和撤銷多個事件
    //通常與事件取消一起使用
   $('li').on('mouseover.hello',function(){ console.log('hello')});
   $('li').on('mouseover.world',function(){ console.log('world')});

   //事件取消 元素.off()  取消該元素的所有事件
   //有參數  元素.off(mouseover) 取消元素的mouseover事件
   $('li').off('mouseover.hello'); //取消元素的mouseover.hello 事件

   //jq中 阻止默認事件+阻止事件冒泡 return false
   $('div').on('click',function(evt){.
     evt.originalEvent //將jq的evt轉成原生的evt
     evt.preventDefault();//js 阻止默認事件
     evt.stopPropagation();// js 阻止事件冒泡
     return false; // jq 阻止默認事件+阻止事件冒泡
   })
    </script>
  • 事件取消
  • 元素.off() 取消該元素的所有事件
  • 元素.off(mouseover) 取消元素的mouseover事件
  • $(‘li’).off(‘mouseover.hello’); //取消元素的mouseover.hello 事件

jq中 阻止默認事件+阻止事件冒泡 return false

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章