javascript中的模式textarea返回undefined

问题描述 投票:0回答:1

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

返回

未捕获的TypeError:无法读取未定义的属性'toLowerCase'

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

未捕获的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>

javascript jquery keyup
1个回答
1
投票

您可以尝试使用call方法调用该函数,传递适当的上下文(textarea对象):

onkeyup="validateTextarea.call(this)"

或者,最好是添加一个事件监听器:

$('textarea').on('keyup', function(e) {
    validateTextarea();
});
© www.soinside.com 2019 - 2024. All rights reserved.