优化点击事件绑定 发表于 2019-01-15 | 更新于 2019-08-10 | 分类于 前端 | 阅读次数: 本文字数: 1.7k | 阅读时长 ≈ 2 分钟 1、优化点击事件绑定 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script></head><body><button data-action="id1">新增按钮1</button><button data-action="id2">删除按钮2</button><button data-action="id3">按钮3</button><button data-action="id4">按钮4</button><script> var log = function () { console.log.apply(console, arguments) } var actionList = { 'id1': function () { alert('id1=============>') }, 'id2': function () { alert('id2===============>') }, 'id3': function () { alert('id3===============>') }, 'id4': function () { alert('id4===============>') } } let $body = $('body') $body.on('click', '[data-action]', function () { //jQuery获取html标签自定义属性值或data值 let action_name = $(this).data('action') let action = actionList[action_name] // log(action) // log($.isFunction(action)) if ($.isFunction(action)) { action() } }) //页面需要新增一个按钮,做扩展 $body.append('<button data-action="id5">按钮5</button>') $.extend(actionList, { 'id5': function () { alert('id5============>') } })</script></body></html> 参考 https://github.com/cssmagic/blog/issues/48 打赏 微信支付 支付宝