Javascript 未捕获的类型错误:无法读取 Jquery 中未定义的属性“修剪”

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

Uncaught TypeError: Cannot read property 'trim' of undefined in Jquery

javascriptjqueryhtml

提问by Saravanan Arunagiri

In Jquery replace the space character to '%20'. but working in other forms not in single form. in consists header as

在 Jquery 中,将空格字符替换为 '%20'。但以其他形式而不是单一形式工作。在包含标题为

<header>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
</header>

the code using in other form its working well.

以其他形式使用的代码运行良好。

var vname = $("#EarningsTypes").val();
vname = vname.trim().replace(/ /g, '%20');
jQuery.noConflict();

回答by Tushar

You're getting error

你得到错误

Uncaught TypeError: Cannot read property 'trim' of undefined in Jquery

未捕获的类型错误:无法读取 Jquery 中未定义的属性“修剪”

that means, the variable vnameis undefined. To prevent this error from occurring, you can use the ternary operator to set the default value of the string to empty string when it is undefined.

这意味着,变量vnameundefined。为防止出现此错误,可以使用三元运算符将字符串的默认值设置为空字符串时undefined

var vname = $("#EarningsTypes").val() == undefined ? '' : $("#EarningsTypes").val().trim();
vname = vname.replace(/ /g, '%20');

You can also use ||to set the default value

也可以使用||来设置默认值

var vname = $("#EarningsTypes").val() || '';


If you're using an older browser that doesn't support trim, you can use polyfill from MDN

如果您使用的是不支持 的旧浏览器,则trim可以使用MDN 中的 polyfill

if (!String.prototype.trim) {
  String.prototype.trim = function() {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}