[英]Uncaught TypeError: Cannot read property toLowerCase of undefined
[英]Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
$('#sum').keydown(function(){
updateResultPrice();
});
function updateResultPrice() {
ajax('/payment/summ', 'price='+$(this).val());
}
不工作! 控制台日志打印:未捕获的TypeError:无法读取未定义的属性'toLowerCase'
您没有对.toLowerCase()
的调用,但是我猜您正在将其链接到.val()
的末尾。
麻烦的是,您的this
值是window
,而不是#sum
元素。
将您的处理程序更改为此:
$('#sum').keydown(updateResultPrice); // <-- pass the function directly
function updateResultPrice() {
ajax('/payment/summ', 'price='+$(this).val().toLowerCase());
}
现在,在调用处理程序时, this
将参考#sum
变量和.val()
将不会返回undefined
。
我按原样测试了您的代码,但实际上没有通过控制台收到“ Uncaught TypeError:无法读取属性'toLowerCase'的未定义”错误。 但是,我确实使用ajax()
方法触发了错误。
您的代码无法正常运行的原因在于$(this)
等于window
而不是#sum
元素。 六个手指的男人的回答确实解释了这一点。
尝试改用此代码。
// Switch 'keydown' to 'on' and include 'keyup' event to get the actual data;
// The 'on' method allows you to "string" events together. 'keyup keydown click focus...' etc.
$('#sum').on('keyup', function(){
// Define a variable to make calling 'this' easier to write;
var me = $(this);
// Get the value of "me";
var val = me.val();
// Relay the value to the function;
updateResultPrice( val );
});
// The function, updateResultPrice, accepts an argument of "value";
function updateResultPrice( value ) {
// Your prior code used $(this).val() within the function;
// The function doesn't have a $(this) to retreive the value from it,
// So, use the "value" argument;
$.ajax('/payment/summ', 'price=' + value); // Call "$.ajax", not "ajax";
// The above snippet will trigger a 404, should the file not exist.
// Just to test that it works, log it to the console;
console.log( 'the price is: '+value );
}
为了您的测试愉快,这里是上述代码的JSFiddle演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.