在 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
也就是说,变量vname
是undefined
。为防止出现此错误,可以使用三元运算符将字符串的默认值为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/