jquery内部的Javascript抛出语句准备好了

javascript throw statement inside jquery ready?

本文关键字:语句 准备好了 Javascript 内部 jquery      更新时间:2023-09-26

所以我想知道如果以下是合法的,也许它不工作由于语法错误。对单个搜索字段进行四个规则的简单验证。感谢您对优雅和启发性解决方案的任何帮助!

 $(function() { 
    $('input.text').focus(function() {
        $(this).removeClass('noSubmitX');
        $('.enterX').removeClass('now').text( orig);
    });  //reset error status
    var orig = "Enter the title you want.";
    var msg1 = "Title must be between 3 and 63 characters.";
    var msg2 = "Title cannot begin or end with a hypen";
    var msg3 = "Title cannot contain a hyphen at character positions 3 and 4";
    $('form.xSearch').submit(function() {
        var theSearch = $('input.text').val();
        var xLong = $('input.text').val().length;
        var firstx = (theSearch[0]);
        var thirdx = (theSearch[2]);
        var fourthx = (theSearch[3]);
        var lastx = (theSearch[xLong - 1]);
        try {
            if (xLong < 2 || xLong > 62) {
                throw "msg1";
            }
            else if (firstx == "-") || (lastx == "-") {
                throw "msg2";
            }
            else if (thirdx == "-") && (fourthx == "-")
            {
                throw "msg3";
            }
        }
        catch (er) {
            if (er == 'msg1') {
                $('input.text').addClass('noSubmitX');
                $('.enterX').addClass('now').text('Title must be between 3 and 63 characters.');
            }
            if (er == 'msg2') {
                $('input.text').addClass('noSubmitX');
                $('.enterX').addClass('now').text('Title cannot begin or end with a hypen');
            }
            if (er == 'msg3') {
                $('input.text').addClass('noSubmitX');
                $('.enterX').addClass('now').text('Title cannot contain a hyphen at character positions 3 and 4');
            }
        }
    });
});

我想你的if声明遇到麻烦了。它们需要用括号括起来,或者像这样括起来:

if (xLong < 2 || xLong > 62) {
    throw "msg1";
}
else if (firstx == "-" || lastx == "-") {
    throw "msg2";
}
else if (thirdx == "-" && fourthx == "-") {
    throw "msg3";
}