我在js中有代码,用于检查Textarea中输入的字符的正确性。 此代码未获得批准。
返回
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
在$.each($(this).val().split("\n"), function () {
未捕获类型错误:无法读取未定义的属性“toLowerCase” 请帮忙
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<table>
<tr>
<td>
<form method = 'post'>
<textarea style="width:50%" rows="5" onkeyup = "validateTextarea()" pattern="^[\x20-\x7F]+$" cols="40" ></textarea>
<input type = "button" value="Save" />
</form>
</td>
</tr>
</table>
<script>
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = '^[\\x20-\\x7F]+$';
// check each line of text
$.each($(this).val().split("\n"), function () {
// check if the line matches the pattern
var hasError = !this.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
// Not supported by the browser, fallback to manual error display...
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$('textarea').attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
}
</script>
最佳答案
您可以尝试使用 call
方法调用该函数,并传递适当的上下文(textarea 对象):
onkeyup="validateTextarea.call(this)"
或者,最好添加一个事件监听器:
$('textarea').on('keyup', function(e) {
validateTextarea();
});
关于javascript - javascript 中的模式文本区域返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54923111/