java 脚本中的模式文本区域 return 未定义

Pattern textarea in java script return undefined

我在js中有代码,用于检查Textarea中输入字符的正确性。 此代码没有工作批准。

Return

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

$.each($(this).val().split("\n"), function () {

Uncaught TypeError: 无法读取未定义的 属性 '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();
});