一、優化點擊事件綁定css
<!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>
複製代碼
參考html
github.com/cssmagic/bl…jquery
本文由博客一文多發平臺 OpenWrite 發佈!git