首页 > 技术文章 > jQuery事件

hhl6 2019-01-17 20:45 原文

jquery 绑定事件:

html中华有如下代码:
<div class="box">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>
<input id="ipt" type="text"> <button id="btn">添加</button>
<div id="wrap">
</div>

给其绑定事件有三种方法如下:

$('.box li').on('click', function(){
    console.log(1)
  var str = $(this).text()
  $('#wrap').text(str)
})

//等同于
$('.box>ul>li').click(function(){
    console.log(2)
  var str = $(this).text()
  $('#wrap').text(str)
})

//也可以这样写
$('.box li').on('click.hello', function(){
    console.log(3)
  var str = $(this).text()
  $('#wrap').text(str)
})
//命名空间没什么特别的作用,只不过在解绑事件时便于区分绑定的事件
$('.box li').off('click.hello')

//可是用如下方法新增的元素是没绑定事件的
$('#btn').on('click', function(){
  var value = $('#ipt').val()
  $('.box>ul').append('<li>'+value+'</li>')
})

在click后面加.hello是有利于解绑事件的

使用事件代理:

$('.box ul').on('click', 'li', function(){
  var str = $(this).text()
  $('#wrap').text(str)
})

//上面代码相当于原生 js 的
document.querySelector('.box ul').addEventListener('click', function(e){
    if(e.target.tagName.toLowerCase() === 'li'){
        //do something
    }
})

 

推荐阅读