优化点击事件绑定

1、优化点击事件绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64


<!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