Javascript 未捕获的类型错误:无法调用未定义的方法“替换”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8918009/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:04:56  来源:igfitidea点击:

Uncaught TypeError: Cannot call method 'replace' of undefined

javascriptjqueryjquery-selectors

提问by wowzuzz

$(this).find("input[name=amount]").val($(this).find("input[name=amount]").val().replace('$', ''));

Keep getting this error on my developer tools. I just want to replace the character $ with nothing which is ''

在我的开发人员工具上不断收到此错误。我只想用 '' 替换字符 $

Thoughts?

想法?

回答by Blender

Your error just says that there is no element that matches your selector, so element.val()is returning undefined, which has no replacemethod. Try debugging it and console.log()at each step.

您的错误只是说没有与您的选择器匹配的元素,因此element.val()返回undefined,它没有replace方法。尝试console.log()在每一步调试它。

Also, you don't need to search for the element twice. Just store it in a variable:

此外,您不需要两次搜索元素。只需将其存储在一个变量中:

var $input = $(this).find('input[name="amount"]');
$input.val($input.val().replace('$', ''));