问题描述
所以我的webapp的非ajax版本是正常的,因为这些事件是按照我想要的顺序添加的,所有的事件都被添加到所讨论的手机元素上。
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.
但是对于我的ajax应用程序,事件被添加不同,因为元素被动态获取,所以我有相同的事件,但实际上在不同的元素容器用于检查动态添加元素,以及直接应用于.input-cell-phone)上的掩码。
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').
例如,当用户类型无效(215) - ### - ####时,我希望Masked Input在我的模糊代码之前清除它,但是它没有。
这里基本上是ajax应用程序(好减去ajax调用,我用.append模拟它):
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/
这是非ajax版本的工作原理我期望如何:
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?
推荐答案
我想到了下面这样做。
所以当我专注于输入,我动态添加事件,如果插件没有添加已经。
我的应用程序中的事件排序有问题。所以我确定我先添加面具,然后我的模糊事件。
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('');
}
});
}
}
});
这篇关于动态添加元素和Masked-Input插件的事件顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!