參數含義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>' } })