事件代理日常总结

js是单线程的,添加事件的时候如果正好加载异步数据,dom节点很有可能没有加载上就已经进入了事件队列,导致dom无法添加事件

        var s = document.querySelector('body');
        var tem;
        s.addEventListener('click', function (e) {
            if (e.target.tagName.toLowerCase() === 'button' &&  e.target.className.indexOf('cancel-order') >= 0) {
                $('#cancel-reason').val('');
                $('#cancel-content').val('');
                tem = $(e.target);
                var info = tem.parent().parent().find('.orderId').text();
                $('#info-order').text(info);
                $('.mask').show();
                $('.jump-layer').show();
            }
        });

以上是我用的事件代理,基本原理就是在父类元素添加事件,这样父类可以在加载前就进入事件队列,可以添加事件,添加事件后自行处理吧。。

同时使用事件代理不用为所有的子类添加事件,这样在有大量的子类时可以减少添加事件的消耗。

/**
 * @file Describe the file
 */
var olTpl = __inline('./selectSpot.tmpl');
module.exports = {
    init: function () {
        var self = this;
        self.$content = $('#content-list');
        $.get('main/gettouristplace', {city_id:2912}, function (data) {
            var data = JSON.parse(data);
            self.$content.append(olTpl(data));
            console.log($('input[type=checkbox]:checked').length);
            console.log($('label .check2').length);
        });
        var s = document.querySelector('body');
        var tem;
        s.addEventListener('click', function (e) {
            if (e.target.tagName.toLowerCase() === 'i' && e.target.className.indexOf('check2') >= 0 && e.target.className.indexOf('iconfont') >= 0)
            {
                console.log(166);
                console.log($('input[type=checkbox]:checked').length);
                console.log($('input[type=checkbox]:checked')); 
                if ($('input[type=checkbox]:checked').length === 10) {
                    console.log(3435);
                    $('input[type=checkbox]').not("input:checked").attr('disabled', 'true');
                    console.log($('input[type=checkbox]').not("input:checked").length);
                }
            }
        });
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值