jQuery each method does not return value

送分小仙女□ 提交于 2019-11-28 08:45:18

问题


$(document).ready(function() {

    $('#commentForm').submit(function(){

        return $('input[type=text], textarea').each(function(index){

            if($(this).attr('value') == ""){
                alert(msgHash[$(this).attr('id')]);
                return false;

            }else{

                if(!$(this).attr('value').match(validateHash[$(this).attr('id')])){
                    //Do nothing
                    alert(msgOnError[$(this).attr('id')]);
                    return false;
                }
            }
        });

        return true;
    });
});

Here msgOnError, msgHash and msgHash are map that I use to get messages for each text box with particular ID Unfortunately each method does not return false to cancel submission of the form. What am I doing wrong ?? I am new to jQuery, Thanks


回答1:


Yes, that's exactly how each works. Since it's actually a loop that calls your anonymous function in each iteration, exiting those functions, will not exit the calling function as well. Returning true and false here, is actually corresponding to the continue and break of the for loop, repsectively.

You're gonna need to set a boolean flag, then return false (break), and then return the value of your boolean flag after the each



来源:https://stackoverflow.com/questions/1900172/jquery-each-method-does-not-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!