事件代理日常总结

来源:互联网 发布:知乎av封面杀手 编辑:程序博客网 时间:2024/05/16 18:01

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
原创粉丝点击