参数含义javascript
同 on,绑定事件,但只执行一次
html
移除一个事件处理函数java
$('.box li').off('click')
根据绑定到匹配元素的给定事件类型执行全部处理程序和行为,即经过代码JS使事件触发.trigger
可自定义事件名称,例以下面例子中自定义名称为 myclick
git
//例如在下面的 demo 案例中 $('.box ul').one('myclick','li',{name: 'evenyao'}, function(e){ var str = $(this).text() console.log(e.data) $('#wrap').text(str) }) //经过执行完setTimeout以后 触发事件 setTimeout(function(){ $('.box li').eq(0).trigger('myclick') },3000)
demo 案例github
<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> <script></script>
$('.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) })
// 命名空间 hello $('.box li').on('click.hello',function(){ console.log('hello') var str = $(this).text() $('#wrap').text(str) }) $('.box li').on('click.world',function(){ console.log('world') var str = $(this).text() $('#wrap').text(str) }) // 命名空间无特别做用,只是在解绑事件时便于区分绑定事件 $('.box li').off('click.hello')
即直接在'click'
以后指定'li'
,便是 jQuery 事件代理的写法app
//但是用以下方法新增的元素是没绑定事件的 $('#btn').on('click', function(){ var value = $('#ipt').val() $('.box>ul').append('<li>'+value+'</li>') }) //咱们能够用事件代理 $('.box ul').on('click', 'li', function(){ var str = $(this).text() $('#wrap').text(str) })
等同于 原生JS 事件代理写法函数
//上面代码至关于原生JS的 document.querySelector('.box ul').addEventListener('click',function(e){ if(e.target.tagName.toLowerCase() === 'li'){ //console.log(e.target) var str = e.target.innerText //console.log(str) document.querySelector('#wrap').innerHTML = '<div id="wrap">' + str + '</div>' } })