jqueyr on()绑定多个动态元素的点击事件不同处理函数

我目前所知道的方法如下:

$(document).on('click','.attachment',function () {

    console.log('attachment点击了')

}).on('click','.amend',function () {

    console.log('amend点击了')

})

但是看网上说on()可以绑定多个事件多个函数:

$(document).on({ 

    click:function(){ //事件1

     ......

    },

    keyup:function() { //事件2

       .......

    },

    keydown:function(){ //事件3

     .......

    }

},'.select1','.select2','select3'); //元素1,2,3

并不能,只能在最后的元素上绑定三个事件,这不是我想要的!我想要的是不同的元素都绑定点击事件处理的函数却不同的方法。

有哪位大神知道麻烦告诉小弟一下,感激不尽


精慕HU
浏览 602回答 1
1回答

FFIVE

什么意思,不想写太多重复的$(document).on么?如果是这样的话,可以把调用的function放在一个对象里面&nbsp;<div class='a aaaaaa aaaaaaa' style="width: 100px;height: 100px;background: #ccc"></div>&nbsp;<div class='b' style="width: 100px;height: 100px;background: #000"></div>&nbsp;<div class='c' style="width: 100px;height: 100px;background: #444"></div>&nbsp;&nbsp;<script>&nbsp;const clickFunc = {&nbsp; &nbsp; &nbsp;a: function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log('aaaaaa');&nbsp; &nbsp; &nbsp;},&nbsp; &nbsp; &nbsp;b: function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log('bbbbbb');&nbsp; &nbsp; &nbsp;},&nbsp; &nbsp; &nbsp;c: function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log('cccccc');&nbsp; &nbsp; &nbsp;}&nbsp;};&nbsp;$(document).on('click', '.a, .b, .c', function(e) {&nbsp; &nbsp; &nbsp;clickFunc[e.target.classList[0]]();&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript