加载元素后,Javascript绑定元素事件

时间:2011-07-28 10:00:21

标签: javascript jquery javascript-events

我是javascript的新手所以maby这是众所周知的/愚蠢的/无用的,但是我想在加载DOM元素后立即让它们发生(在这个网站或google上找不到任何搜索,但它很难用很少的词来解释这一点。例如,当加载大页面时,我想隐藏/添加onlick事件/等。元素一出现在用户屏幕上而不是$(document).ready()。我写了一个简单的类(仅用于训练,闭包对我来说是新的,所以可能存在很多错误),它可以做我想要的但是我想用更好的东西用于商业用途(在我正在帮助开发的网站上)。这是我的源代码 - maby它会解释我想要的更好的帖子:我也是新来的英语(:

function MY_loader() {
    function container() {
        this.add_event = function(new_event,obj_selector,settings) {
            if(typeof(settings)!='object') {
                settings={};
            }
            if(typeof(settings.event_id)!='string') {
                settings.event_id=gen_new_event_id();
            }
            settings=$.extend({},default_settings,settings);
            settings.obj_selector=obj_selector;
            settings.event=new_event;
            events[settings.event_id]=settings;
        }

        this.execute_events = function(if_force) {
            if(typeof(if_force)=='undefined') {
                if_force=false;
            }
            if(html_is_loaded&&!if_force) {
                return;
            }
            var temp_obj;
            for(var event_name in events) {
                temp_obj=$(events[event_name].obj_selector);
                if(temp_obj.length || (html_is_loaded && events[event_name].if_force)) {
                    temp_obj.each(function() {
                        if(events[event_name].expect_multiple) {
                            if($(this).data('my_loader_'+events[event_name].event_id+'_executed')) {

                                return;
                            }
                        }
                        if(events[event_name].event_type!='func') {
                            $(this).bind(events[event_name].event_type+'.'+events[event_name].event_id,events[event_name].event);
                        }
                        else {
                            events[event_name].event($(this));
                        }
                        if(events[event_name].expect_multiple) {
                            alert('here');
                            $(this).data('my_loader_'+events[event_name].event_id+'_executed',1);
                        }
                    });
                       //alert(events[event_name].obj_selector+' '+events[event_name].event_type);
                    if(!events[event_name].expect_multiple) {
                        delete events[event_name];
                    }
                }
            }
            if(!html_is_loaded) {
               var cur_time=new Date().getTime();
               setTimeout('MY_loader().execute_events();',Math.max(Math.min(tick_time-(cur_time-last_tick_time),tick_time),0,min_tick_diff));
               last_tick_time=cur_time;
            }
        }

        this.html_is_loaded_set=function(if_html_is_loaded) {
            html_is_loaded=if_html_is_loaded?true:false;
        };

        this.html_is_loaded_get=function() {
            return html_is_loaded?true:false;
        };

        return this;
    }
    function instance(if_strat) {
        if(typeof(class_is_loaded)=='undefined'||!class_is_loaded) {
            load_class();
        }
        return container(if_strat);
    }

    var load_class=function() {
        this.class_is_loaded=true;
        this.events = {};
        this.allowed_event_id_chars='abcdefghijklmnopqrstuvwxyz0123456789';
        this.default_settings={
            'event_type':'click',
            'if_force':false,
            'expect_multiple':false
        };
        this.tick_time=500;
        this.min_tick_diff=100;
        this.last_tick_time=0;
        this.html_is_loaded=false;
        MY_loader().execute_events();
        $(document).ready(function(){
            MY_loader().html_is_loaded_set(true);
            MY_loader().execute_events(true);
        });
    }

    var gen_new_event_id=function() {
        for(var new_id=gen_random_id();typeof(events[new_id])!='undefined';new_id=gen_random_id());
        return new_id;
    }

    var gen_random_id=function() {
        var allowed_event_id_chars_size=allowed_event_id_chars.length;
        var new_id='';
        for(var i=0;i<10;i++) {
            new_id+=allowed_event_id_chars[get_random_int(0,allowed_event_id_chars_size-1)];
        }
        return new_id;
    }

    function get_random_int(min, max)
    {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    return new instance();
}
//Add click event to #some_selector (once and dont check after it)
MY_loader().add_event(function() {
    alert($(this).val());
}, '#some_selector');
//Hide elements as soon as they are loaded.
//We expect multiple elements with this selector, so it will
//check for this elements untill document is loaded, but this function
//will be applied only one time for each element.
MY_loader().add_event(function(obj) {
    obj.hide();
    alert('This should happen before DOM is completely loaded!');
}, '.some_other_selector',{'event_type':'func','expect_multiple':true});
//This alert should be outputted the last
$(document).ready(function(){
    alert('Document is fully loaded!');
});

提前谢谢大家!

UPD:为了让这个问题更有趣,因为我必须补充一点:大多数浏览器在完全加载之前开始页面渲染(这似乎由于某些原因而不为人所知),这里是一些链接:

  1. http://en.wikipedia.org/wiki/Incremental_rendering
  2. When do browsers start to render partially transmitted HTML?
  3. http://www.vbulletin.org/forum/showthread.php?t=161099
  4. 所以,我的问题应该更广为人知,因为这个增量页面加载会给开发人员带来很多问题:用户可以在加载页面之前点击非工作按钮,加载javascript时隐藏的一些东西可能会显示出来可能是丑陋的等等(这是我的问题的例子)。其他开发人员会忽略这个问题吗?如果我错了,请纠正我。

1 个答案:

答案 0 :(得分:0)

如果您担心的是您不希望用户在最终版本之前看到该页面,您可以直接进行DOM修改,例如:

<a href="#" id="test">Test</a>
<script type="text/javascript" src="enhancePage.js"></script>

因为在解析脚本之前,DOM中存在有问题的节点,所以您可以使用它。