javascript - 未捕获的类型错误 : Cannot read property 'trim' of undefined in Jquery

标签 javascript jquery html

在 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>

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

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

最佳答案

你遇到了错误

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

也就是说,变量vnameundefined。为防止出现此错误,可以使用三元运算符将字符串的默认值为undefined时的空字符串。

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

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

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

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

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

关于javascript - 未捕获的类型错误 : Cannot read property 'trim' of undefined in Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32733423/

相关文章:

jquery - 错误 javascript 无法从属性值获取值

html - 可以从 webkitStorageInfo.queryUsageAndQuota() 获取详细信息

javascript - 当选中第 n 个复选框时,针对某个类的第 n 个元素?

javascript - 为什么 FB.login 不删除注销 cookie?

JavaScript。在 setTimeout 函数中分配错误的值

javascript - 你如何加载 2 个 javascript 文件,它们之间可能有公共(public)变量并在 HTML 页面上访问它?

javascript - 我将在哪里使用带有谷歌闭包的函数注释?

jquery - IE 中的 Colorbox - 加载外部页面,尝试下载内容,而不是播放

javascript - JQuery/Javascript 函数破坏了 $(this) (我认为)

JavaScript 自动解码 PHP 通过 HTML <div> 数据属性发送的 JSON?