我正在尝试重构我的js代码以使其更加干燥,但是却遇到了这个错误。这是我的代码
function validate_field(e){
console.log(typeof e);
$(e).focusout(function(e){
var price = $(e).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(e).val(0);
}
})
}
$(function(){
validate_field('#price');
})
根据堆栈跟踪错误在这里某处var price = $(e).val();
我在这里缺少什么?
答案 0 :(得分:5)
尝试
function validate_field(e){
console.log(typeof e);
$(e).focusout(function(ev){
-------------------------------^ here you are redeclaring the e previously passed as selector
var price = $(e).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(e).val(0);
}
})
}
$(function(){
validate_field('#price');
})
答案 1 :(得分:4)
您正在使用e
函数变量干扰e
参数。它应该是:
function validate_field(s) { // here also ? I have set "s" as parameter, you can set any word you like
console.log(typeof s); // noticed the difference here?
$(s).focusout(function(e) { // noticed the difference here?
var price = $(this).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(e).val(0);
}
});
}
您也可以像@dakait那样更改您的事件参数以进行微小更改。
答案 2 :(得分:0)
重新分配变量会导致问题。
function validate_field(field){ // both variable should not be same e & 'e' of inside function
console.log(typeof e);
$(field).focusout(function(e){
var price = $(field).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(field).val(0);
}
})
}
$(function(){
validate_field('#price');
})
或
可以直接使用以下代码而无需调用脚本中的其他功能
$(function(){
$('#price').focusout(function(e){
var price = $(this).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(this).val(0);
}
})
});