Javascript 未捕获的类型错误:无法读取未定义的属性“toLowerCase”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27192047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
提问by Данила Андреев
$('#sum').keydown(function(){
updateResultPrice();
});
function updateResultPrice() {
ajax('/payment/summ', 'price='+$(this).val());
}
Not working! Console log print: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
不工作!控制台日志打印:未捕获的类型错误:无法读取未定义的属性“toLowerCase”
回答by six fingered man
You don't have a call to .toLowerCase(), but I'm guessing you're chaining it to the end of .val().
您没有调用.toLowerCase(),但我猜您将它链接到.val().
The trouble is that your thisvalue is window, and not the #sumelement.
问题是你的this值是window,而不是#sum元素。
Change your handler to this:
将您的处理程序更改为:
$('#sum').keydown(updateResultPrice); // <-- pass the function directly
function updateResultPrice() {
ajax('/payment/summ', 'price='+$(this).val().toLowerCase());
}
Now when the handler is invoked, thiswill reference the #sumvariable and .val()will not returnundefined.
现在,当调用处理程序时,this将引用该#sum变量并且.val()不会返回undefined.
回答by LeoV117
I tested your code, as is, and didn't actually get the "Uncaught TypeError: Cannot read property 'toLowerCase' of undefined" error through the console. However, I did manage to trigger an error with the ajax()method.
我按原样测试了您的代码,但实际上并没有通过控制台收到“Uncaught TypeError: Cannot read property 'toLowerCase' of undefined”错误。但是,我确实设法触发了该ajax()方法的错误。
The reason your code wasn't working, was down to the fact of $(this)would equal the window, and not the #sumelement. six fingered mandid explain this in his answer.
您的代码无法正常工作的原因归结为$(this)将等于window,而不是#sum元素。六指男人在他的回答中确实解释了这一点。
Try using this code instead.
尝试改用此代码。
// 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 );
}
For your testing pleasures, here's a JSFiddledemo of the above code.
为了您的测试乐趣,这里是上述代码的JSFiddle演示。

