优化点击事件绑定

Posted by 小兵兵 on Tuesday, January 15, 2019

目录

1、优化点击事件绑定



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