基于jQuery的事件绑定插件

本文介绍了一个遵循UMD规范的jQuery事件绑定插件,支持自定义属性绑定和多种事件类型。插件在浏览器环境中需支持ES6,使用时需要先引入jQuery库。示例代码展示了如何初始化插件并绑定输入框的输入事件、按钮的点击和双击事件。插件会根据元素上的特定属性自动绑定对应的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于jQuery的事件绑定插件

遵循UMD规范,浏览器环境需支持ES6

使用说明
  • 引用文件前需引入jQuery.js
  • 第一个参数为需要绑定事件函数的对象
  • 支持自定义属性绑定,属性前缀默认值为v,传值通过初始化第二个参数传入字符串
  • 支持多种事件类型,传值通过初始化第三个参数传入数组,默认值为[‘click’, ‘dblclick’, ‘contextmenu’, ‘mousedown’, ‘mouseup’, ‘keyup’, ‘focus’, ‘blur’, ‘change’, ‘input’]
  • 初始化插件方法
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>demo</title>
	</head>
	<body>
		<div>
			<input type="text" v-input="doing"/>
			<button class="btn" v-click="confirm">确认</button>
			<button class="btn" v-dblclick="cancel">取消</button>
		</div>
	</body>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script src="./event_bind.js"></script>
	<script type="text/javascript">
		// 初始化插件
		new $.eventBind({
			doing() {
				console.log('输入框正在输入...');
			},
			confirm() {
				console.log('点击确认按钮');
			},
			cancel() {
				console.log('双击取消按钮');
			}
		});
	</script>
</html>

event_bind.js:

/**
 * 绑定事件插件
 * create by ningh at 20220222
 */
!function (root, factory) {
    if (typeof exports === 'object' && typeof module !== 'undefined') {
        module.exports = factory(require('jquery'));
    } else if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else {
        factory(root.jQuery);
    }
}(this, function ($) {
    $.extend({
        eventBind: class {
            constructor(fnObj, prefix, events) {
                this.prefix = prefix || 'v'; // 属性名前缀
                this.events = events || ['click', 'dblclick', 'contextmenu', 'mousedown', 'mouseup', 'keyup', 'focus', 'blur', 'change', 'input']; // 默认支持的事件类型
                this.eventBind(fnObj);
            }
    
            /**
             * @param {object} fnObj 装有绑定函数的对象
             */
            eventBind (fnObj) {
                let prefix = this.prefix,
                    events = this.events,
                    selector = events.map(e => `[${prefix}-${e}]`),
                    $eles = this.$eles = $(selector.join(',')),
                    attrBinds = this.attrBinds = {},
                    attrName = '',
                    attrValue = '',
                    eventType = '';
    
                $eles.each(function () {
                    let attr;
                    for (let i = 0, len = events.length; i < len; i++) {
                        attr = this.attributes[`${prefix}-${events[i]}`];
                        if (attr) { // 属性存在
                            attrName = attr.name;
                            attrValue = attr.value;
                            eventType = events[i];
                            break;
                        }
                    }
                    if (!attr) {
                        console.warn('没有配置该事件类型', this);
                        return true;
                    }
                    if (!attrValue) {
                        console.warn(`${prefix}-${eventType}属性值不能为空`, this);
                        return true;
                    }
                    if (!fnObj[attrValue]) {
                        console.warn(`找不到事件绑定函数:${attrValue}()`);
                        return true;
                    }
                    if (typeof fnObj[attrValue] !== 'function') {
                        console.warn(`请声明正确的事件绑定函数:${attrValue}()`);
                        return true;
                    }
                    if (attrBinds[attrValue] && attrBinds[attrValue] == attrName) { // 相同属性值只绑定一次
                        return true;
                    }
                    $($eles.context).off(eventType, `[${attrName}="${attrValue}"]`).on(eventType, `[${attrName}="${attrValue}"]`, $(this).data(), fnObj[attrValue].bind(fnObj));
                    attrBinds[attrValue] = attrName;
                });
            }
        }
    });
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值