Order of events for dynamically added elements and Masked-Input plugin

我的梦境 提交于 2019-12-25 01:14:18

问题


So the non-ajax version of my webapp is fine, cause the events are added in the order I want and all the events are added on the cell-phone element in question.

But for my ajax app, the events are added 'differently' since the elements are dynamically gotten, so I have the same events but actually on different elements (on '#container' for checking dynamic added elements, and a mask applied directly on '.input-cell-phone').

For example, when user types invalid (215)-###-####, i expect Masked Input to clear it out before my blur code but it doesnt. Here is basically the 'ajax' app (well minus the ajax call, i simulate it with .append):
http://jsfiddle.net/armyofda12mnkeys/9DGgF/

Here is the non-ajax version that works like how I expect:
http://jsfiddle.net/armyofda12mnkeys/XKf8d/2/

Any ideas how to get this to work?


回答1:


I came up with just doing it this way below. so when i focus on the input, i dynamically add the event if the plugin has'nt been added already. There was an issue with event ordering in my app. so i make sure i add the mask first, then my blur event.

$('#container').on('focusin', '.input-phone', function() {
    var $this = $(this);
    if( (typeof $this.data()['rawMaskFn'] !== "function") ) {
        //dynamically adds the mask plugin
        $this.mask("(999)-999-9999"); //probably adds a blur event

        //make sure its the first thing in blur event
        if($this.hasClass('input-cell-phone')) { //********* moved here so this blur event can get added after the above event

            $('.input-cell-phone').blur(function() {//on() way doesnt work here for some reason
                //if clear cell phone, make sure to clear daytime phone
                var phone_val = $.trim($(this).val());
                if(phone_val==""){
                    //find daytime equivilent and clear too
                    $(this).parents('.container').find('input.input-day-phone').val('');
                }
            });
        }
    }
});


来源:https://stackoverflow.com/questions/9946500/order-of-events-for-dynamically-added-elements-and-masked-input-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!