我正在尝试做一个只接受数字的输入。我可以有一些动态输入,所以我使用.live
函数。
在我的.live('keyup')
函数上,我添加了一些","这取决于输入长度。下面是我的一部分关于输入(非动态)的代码:
$(document).ready(function(){
$('#test').change(function() {
alert('trigger change');
});
});
$('#test').live('keyup', function() {
var realDotPos = $(this).val().indexOf('.');
var inputValue = '';
var inputDecimals = '';
var value = '';
var length = 0;
var cptMod = 0;
var cptVirgule = 0;
if (realDotPos == -1){
inputValue = $(this).val().replace(/,/g, '');
} else{
inputValue = $(this).val().substring(0,realDotPos).replace(/,/g, '');
inputDecimals = $(this).val().substring(realDotPos);
}
length = inputValue.length;
if (length > 3){
for(i=length-1; i>=0; --i){
if ((cptMod != 0) && (cptMod % 3 == 0)){
value += ',' + inputValue[i];
++cptVirgule;
} else{
value += inputValue[i];
}
++cptMod;
}
value = value.split('').reverse().join('');
$(this).val(value + inputDecimals);
} else{
$(this).val(inputValue + inputDecimals);
}
});
问题在于,在ie中,当我单击输入时,.change
功能不会触发。FF或铬工作良好。如果我删除线$(this).val(inputValue + inputDecimals);
触发器工作。怎么了?
我创建了这个jsfiddle来测试您的代码。
change事件对我来说在chrome中不触发,也不像在IE中。
你能做的是通过调用.change()
:
$(this).val(value + inputDecimals).change(); // or with .trigger('change')
事件代表团:
.live()
在较新版本的jQuery中已被弃用,您应该查找.on()
(如果您也不使用最新版本,请检查.delegate())
使用。on()和选择器将委托事件处理,从而处理初始化后插入dom中的任何元素(由选择器表示)。
这里我委托给文档,event change/keyup用于所有具有类'。myinput'的内部元素:
我已经为您做了一个小提琴来显示更新的代码,以及它是如何在添加动态新输入时工作的:http://jsfiddle.net/didierg/xw7SV/9/
下面是更新后的js代码(包括优化和事件委托):
$(document).ready(function() {
$(document).on('change', '.myinput', function(e) {
alert('trigger change');
});
$('#test').on('keyup', '.myinput', function(e) {
var $this = $(this), // select 'this' only once
currval =$this.val(), // keep the initial value to work with
newvalue = null,
realDotPos = currval.indexOf('.'),
inputValue = '',
inputDecimals = '',
value = '',
length = 0,
cptMod = 0,
cptVirgule = 0;
if (realDotPos == -1) {
inputValue = currval.replace(/,/g, '');
} else {
inputValue = currval.substring(0,realDotPos).replace(/,/g, '');
inputDecimals =currval.substring(realDotPos);
}
length = inputValue.length;
if (length > 3) {
for(i=length-1; i>=0; --i) {
if ((cptMod != 0) && (cptMod % 3 == 0)){
value += ',' + inputValue[i];
++cptVirgule;
} else{
value += inputValue[i];
}
++cptMod;
}
value = value.split('').reverse().join('');
newvalue = value + inputDecimals;
} else {
newvalue = inputValue + inputDecimals;
}
$this.val(newvalue).change(); // call .change() to trigger the event
});
});
一些笔记对你的代码:
你应该保存你的选择:
var $this = $(this);
与值一样,获取一次:
var val = $this.val()