jQueryUI模態(tài)表單瘋狂踩坑-創(chuàng)新互聯(lián)

想套用一下前端的組件寫一個表單驗證的頁面,于是試了一下jQuery UI

公司主營業(yè)務(wù):成都網(wǎng)站建設(shè)、成都做網(wǎng)站、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)公司是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)公司推出華陰免費做網(wǎng)站回饋大家。

官網(wǎng)的例子

首先把官網(wǎng)的例子貼上:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Dialog - Modal form</title>
    <link rel="stylesheet" >
    <link rel="stylesheet" href="/resources/demos/style.css">
    <style>
        label, input { display:block; }
        input.text { margin-bottom:12px; width:95%; padding: .4em; }
        fieldset { padding:0; border:0; margin-top:25px; }
        h2 { font-size: 1.2em; margin: .6em 0; }
        div#users-contain { width: 350px; margin: 20px 0; }
        div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
        div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
        .ui-dialog .ui-state-error { padding: .3em; }
        .validateTips { border: 1px solid transparent; padding: 0.3em; }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $( function() {
            var dialog, form,
                // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
                emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
                name = $( "#name" ),
                email = $( "#email" ),
                password = $( "#password" ),
                allFields = $( [] ).add( name ).add( email ).add( password ),
                tips = $( ".validateTips" );

            function updateTips( t ) {
                tips
                    .text( t )
                    .addClass( "ui-state-highlight" );
                setTimeout(function() {
                    tips.removeClass( "ui-state-highlight", 1500 );
                }, 500 );
            }

            function checkLength( o, n, min, max ) {
                if ( o.val().length > max || o.val().length < min ) {
                    o.addClass( "ui-state-error" );
                    updateTips( "Length of " + n + " must be between " +
                        min + " and " + max + "." );
                    return false;
                } else {
                    return true;
                }
            }

            function checkRegexp( o, regexp, n ) {
                if ( !( regexp.test( o.val() ) ) ) {
                    o.addClass( "ui-state-error" );
                    updateTips( n );
                    return false;
                } else {
                    return true;
                }
            }

            function addUser() {
                var valid = true;
                allFields.removeClass( "ui-state-error" );
                valid = valid && checkLength( name, "username", 3, 16 );
                valid = valid && checkLength( email, "email", 6, 80 );
                valid = valid && checkLength( password, "password", 5, 16 );
                valid = valid && checkRegexp( name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter." );
                valid = valid && checkRegexp( email, emailRegex, "eg. ui@jquery.com" );
                valid = valid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
                if ( valid ) {
                    $( "#users tbody" ).append( "<tr>" +
                        "<td>" + name.val() + "</td>" +
                        "<td>" + email.val() + "</td>" +
                        "<td>" + password.val() + "</td>" +
                        "</tr>" );
                    dialog.dialog( "close" );
                }
                return valid;
                }

            dialog = $( "#dialog-form" ).dialog({
                autoOpen: false,
                height: 400,
               width: 350,
                modal: true,
                buttons: {
                    "Create an account": addUser,
                    Cancel: function() {
                        dialog.dialog( "close" );
                    }
                },
                close: function() {
                    form[ 0 ].reset();
                    allFields.removeClass( "ui-state-error" );
                }
            });

            form = dialog.find( "form" ).on( "submit", function( event ) {
                event.preventDefault();
                addUser();
            });

            $( "#create-user" ).button().on( "click", function() {
                dialog.dialog( "open" );
            });
        });
    </script>
</head>
<body>
<div id="dialog-form" title="Create new user">
    <p class="validateTips">All form fields are required.</p>
    <form>
        <fieldset>
            <label for="name">Name</label>
            <input type="text" name="name" id="name" value="Jane Smith" class="text ui-widget-content ui-corner-all">
            <label for="email">Email</label>
            <input type="text" name="email" id="email" value="jane@smith.com" class="text ui-widget-content ui-corner-all">
            <label for="password">Password</label>
            <input type="password" name="password" id="password" value="xxxxxxx" class="text ui-widget-content ui-corner-all">
            <!-- Allow form submission with keyboard without duplicating the dialog button -->
            <input type="submit" tabindex="-1" >
        </fieldset>
    </form>
</div>

<div id="users-contain" class="ui-widget">
    <h2>Existing Users:</h2>
    <table id="users" class="ui-widget ui-widget-content">
        <thead>
        <tr class="ui-widget-header ">
            <th>Name</th>
            <th>Email</th>
            <th>Password</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>John Doe</td>
            <td>john.doe@example.com</td>
            <td>johndoe1</td>
        </tr>
        </tbody>
    </table>
</div>
<button id="create-user">Create new user</button>
</body>
</html>

試了一下,一切都很美好。

From表單DIV的位置

首先看到CSS寫的很粗,比如第一條:

label, input { display:block; }

直接就定義了所有l(wèi)abel和input標(biāo)簽的樣式??粗鴅ody里是2個DIV,于是想把2個div外面再包一層div,像下面這樣:

<body>
<div id="myui">
    <div id="dialog-form" title="Create new user"></div>
    <div id="users-contain" class="ui-widget"></div>
</div>
</body>

然后所有的css樣式前面都加上自己的這個div,就不會和別的樣式?jīng)_突了,比如這樣:

#myui label, #myui input { display:block; }

問題:修改后,模態(tài)框里的css樣式都沒有應(yīng)用上。比如lable和input沒有變成塊級標(biāo)簽,導(dǎo)致沒有換行
原因:這里 id="dialog-form" 這個div的位置變了,跑到了 id="myui" 這個div的外面了。造成這個情況的原因是,jQuery UI就是這么做的,把 id="dialog-form" 這個div挖出來,出來好之后append到一個位置,而默認(rèn)位置是 body 標(biāo)簽。
解決方法:知道原因后,修改css的寫法也是可以實現(xiàn)的。但是也是有方法按照原來想的那樣,讓 id="dialog-form" 這個div仍然放在 id="myui" 里面的。在dialog里加上一個 appendTo 參數(shù),指定模態(tài)框要添加的位置,之前沒有指定就是默認(rèn)(body):

dialog = $( "#dialog-form" ).dialog({
                appendTo: '#myui',
                autoOpen: false,
                height: 400,
               width: 350,
                modal: true,
                buttons: {
                    "Create an account": addUser,
                    Cancel: function() {
                        dialog.dialog( "close" );
                    }
                },
                close: function() {
                    form[ 0 ].reset();
                    allFields.removeClass( "ui-state-error" );
                }
            });

實際有2個提交的按鈕

在提交表單之前,先要知道,實際這個例子中有2個按鈕可以用來提交的。其中一個隱藏了。
寫在form里的submit按鈕:

<!-- Allow form submission with keyboard without duplicating the dialog button -->
            <input type="submit" tabindex="-1" >

實際位置應(yīng)該是跑到屏幕外面去了。這里把style屬性去掉就能看到了。這個按鈕的作用是方便我們用鍵盤的回車鍵操作的。
另外jQuery UI幫我們生成的按鈕是在 dialog = $( "#dialog-form" ).dialog() 里用buttons屬性生成的,這里可以自定義以及添加更多的按鈕:

    buttons: {
                    "Create an account": addUser,
                    Cancel: function() {
                        dialog.dialog( "close" );
                    }
                },

另外這里的確認(rèn)按鈕不是submit,而是觸發(fā)一個addUser進行表單驗證的方法。addUser里驗證通過后會生成前端的標(biāo)簽,在前端添加一行數(shù)據(jù),但是submit提交。

表單無法提交

演示的代碼是一個純前端的實現(xiàn),如果要提交到后端,那么就是在form標(biāo)簽里加上action屬性。然后先把submit按鈕的style屬性去掉,用submit先提交。
問題:后端收不到發(fā)來的請求
原因:前端阻止了submit事件的默認(rèn)操作,具體就是下面這句

form = dialog.find( "form" ).on( "submit", function( event ) {
                event.preventDefault();  // 這句的意思就是取消事件的默認(rèn)操作
                addUser();
            });

解決方法:這里直接把阻止的代碼注釋掉就好了
現(xiàn)在可以使用回車鍵進行submit提交了,但是確認(rèn)按鈕并不能提交

問題2:確認(rèn)按鈕不是submit
原因:這個按鈕綁定的是addUser,而addUser里也沒有submit提交
解決方法:把確認(rèn)按鈕的click綁定為觸發(fā)form的submit事件,這樣這個確認(rèn)按鈕的效果就和submit一樣了,而且submit里也是要先執(zhí)行addUser()進行驗證的。把 dialog = $( "#dialog-form" ).dialog() 里用buttons屬性改成了下面這樣,這個buttons的參數(shù)是可支持 Object 和 Array 兩種形式,這里我改用了Array的形式:

buttons: [
                {text: "確認(rèn)", click: function () {
                        form.submit();
                    }},
                {text: "取消", click: function () {
                        dialog.dialog('close');
                    }
                }
            ],

請求的表單內(nèi)容為空

現(xiàn)在后端可以收到請求了,但是收到的都是沒有值的空的請求。
問題:后端內(nèi)收到請求,但是請求的值都是空值
原因:前端在發(fā)送submit請求前,清空了表單的內(nèi)容。在 dialog = $( "#dialog-form" ).dialog() 里最后有一個close屬性,值是一個方法:

    close: function() {
                    form[ 0 ].reset();
                    allFields.removeClass( "ui-state-error" );
                }

close屬性是在對話框關(guān)閉的時候要執(zhí)行的內(nèi)容,這里面清空了form表單的內(nèi)容。
具體步驟是,submit事件會首先觸發(fā)addUser()進行表單驗證。addUser()里面會先用 checkLength() 驗證長度,然后用 checkRegexp() 進行正則的驗證。如果驗證失敗會返回false組織之后事件的發(fā)生。如果驗證通過則會先執(zhí)行關(guān)閉模態(tài)框的操作:

        dialog.dialog( "close" );

這里就要關(guān)閉模態(tài)框了,然后返回true,之后才是執(zhí)行submit提交的動作。但是關(guān)閉模態(tài)框的時候,數(shù)據(jù)就清空了。服務(wù)的收到的就是被清空后的空表單發(fā)來的請求,并且是在通過了前端的數(shù)據(jù)驗證之后的。
解決方法:應(yīng)該可以先不關(guān)閉模態(tài)框,等submit提交之后再關(guān)閉。不過實現(xiàn)起來也不方便。表單清空的功能還是有用的,但是只要在下次打開前清空就好了。這里可以用一個open方法替代原來的close方法。
另外一個坑:官網(wǎng)的頁面里是有一個create方法的,本來想用這個的。但是發(fā)現(xiàn)沒有用,然后去源碼里找了一下(jquery-ui.js):

$.widget( "ui.dialog", {
    version: "1.12.1",
    options: {
        appendTo: "body",
        autoOpen: true,
        buttons: [],
        classes: {
            "ui-dialog": "ui-corner-all",
            "ui-dialog-titlebar": "ui-corner-all"
        },
        closeOnEscape: true,
        closeText: "Close",
        draggable: true,
        hide: null,
        height: "auto",
        maxHeight: null,
        maxWidth: null,
        minHeight: 150,
        minWidth: 150,
        modal: false,
        position: {
            my: "center",
            at: "center",
            of: window,
            collision: "fit",

            // Ensure the titlebar is always visible
            using: function( pos ) {
                var topOffset = $( this ).css( pos ).offset().top;
                if ( topOffset < 0 ) {
                    $( this ).css( "top", pos.top - topOffset );
                }
            }
        },
        resizable: true,
        show: null,
        title: null,
       width: 300,

        // Callbacks
        beforeClose: null,
        close: null,
        drag: null,
        dragStart: null,
        dragStop: null,
        focus: null,
        open: null,
        resize: null,
        resizeStart: null,
        resizeStop: null
    },

上面的Callbacks應(yīng)該就是所有的方法了,并沒有create。然后才試的open。

優(yōu)化-調(diào)整模態(tài)框大小

還是這個生成模態(tài)框的函數(shù) dialog = $( "#dialog-form" ).dialog() ,里面的 height 和 width 屬性,可以設(shè)置模態(tài)框的默認(rèn)大小
問題:這里模態(tài)框有可能會出現(xiàn)滾輪
原因:模態(tài)框 id="dialog-form" 這個div里有這個樣式 overflow: auto ,所以溢出會出現(xiàn)滾動條。
解決方法:把overflow樣式覆蓋掉應(yīng)該就可以了,不過根本問題是溢出。我這里造成溢出的標(biāo)簽是form里的input標(biāo)簽。樣式是這樣的:

input.text { margin-bottom:12px; width:95%; padding: .4em; }

這里我調(diào)整了 width 的寬度就好了。

優(yōu)化-直接隱藏模態(tài)框

例子中沒有這個情況,但是我用的時候頁面加載的時候會首先顯示出模態(tài)框,等加載完畢后模態(tài)框會隱藏掉。
問題:加載頁面的時候會有一瞬出現(xiàn)模態(tài)框
原因:因為我把js代碼的位置放到的最后,所以模態(tài)框的標(biāo)簽的代碼讀完的時候會顯示出來,等js代碼讀取完的時候才會隱藏
解決方法:應(yīng)該把生成模態(tài)框的js主要是 dialog = $( "#dialog-form" ).dialog() 方法提到前面就好了。不過我用了另外一個方法,給我的模態(tài)框的div標(biāo)簽加上了這個類:

<div class="ui-helper-hidden" id="dialog-form" title="Create new user">

jquery-ui.css 里,這個類是這樣的:

.ui-helper-hidden {
    display: none;
}

就是簡單的隱藏掉,試過之后依然可以顯示出來。

修改后的版本

替換掉了模板語言的部分,我用的修改后的版本如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" >
    <style>
        #jqui-dialog label, #jqui-dialog input { display:block; }
        #jqui-dialog form input { margin-bottom:12px; width: 92%; padding: .4em; }
        #jqui-dialog fieldset { padding:0; border:0; margin-top:25px; }
        #jqui-dialog h2 { font-size: 1.2em; margin: .6em 0; }
        #jqui-dialog div#users-contain { width: 350px; margin: 20px 0; }
        #jqui-dialog div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
        #jqui-dialog div#users-contain table td, #jqui-dialog div#users-contain table th {
            border: 1px solid #eee;
            padding: .6em 10px;
            text-align: left;
        }
        #jqui-dialog .ui-dialog .ui-state-error { padding: .3em; }
        #jqui-dialog .validateTips { border: 1px solid transparent; padding: 0.3em; }
    </style>
</head>
<body>
<div id="jqui-dialog">
    <div class="ui-helper-hidden" id="dialog-form" title="添加新用戶組">
        <p class="validateTips">請?zhí)顚懸陆ǖ慕M的名稱</p>
        <form action="." method="post">
            <fieldset>
                <label for="group_name">組名稱</label>
                <input type="text" name="group_name" id="group_name" class="text ui-widget-content ui-corner-all">
                <label for="comments">備注</label>
                <input type="text" name="comments" id="comments" class="text ui-widget-content ui-corner-all">
                <!-- Allow form submission with keyboard without duplicating the dialog button -->
                <input type="submit" tabindex="-1" >
            </fieldset>
        </form>
    </div>

    <div id="users-contain" class="ui-widget">
        <h2>用戶組列表:</h2>
        <button id="create-user">添加新用戶組</button>
        <table id="users" class="ui-widget ui-widget-content">
            <thead>
            <tr class="ui-widget-header ">
                <th>id</th>
                <th>群組名</th>
                <th>備注</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>1</td>
                <td>測試一</td>
                <td>test1</td>
            </tr>
            <tr>
                <td>2</td>
                <td>測試2</td>
                <td>test2</td>
            </tr>
            <tr>
                <td>3</td>
                <td>測試三</td>
                <td>test3</td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
    var dialog, form,
        group_name = $('#group_name'),
        comments = $('#comments'),
        allFields = $([]).add(group_name).add(comments),
        tips_msg = null,
        tips = $('.validateTips');

    // 長度驗證
    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips(n + "的長度必須在" +
                min + "與" + max + "之間。");
            return false
        } else {
            return true
        }
    }

    // 正則驗證
    function checkRegexp(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass("ui-state-error");
            updateTips(n);
            return false
        } else {
            return true
        }
    }

    // 顯示錯誤信息
    function updateTips(t) {
        tips_msg = tips_msg || tips.text();
        tips.text(t).addClass("ui-state-highlight");
        setTimeout(function () {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }

    function addUser() {
        var valid = true;
        allFields.removeClass("ui-state-error");
        valid = valid && checkLength(group_name, "組名稱", 3, 32);
        valid = valid && checkLength(comments, "備注", 0, 64);
        valid = valid && checkRegexp(group_name, /^[^0-9]/, "組名稱不能以數(shù)字開頭");
        if (valid) {
            $( "#users tbody" ).append( "<tr>" +
                "<td>" + 'x' + "</td>" +
                "<td>" + group_name.val() + "</td>" +
                "<td>" + comments.val() + "</td>" +
                "</tr>" );
            dialog.dialog('close');
        }
        return valid
    }

    dialog = $("#dialog-form").dialog({
        appendTo: '#jqui-dialog',
        autoOpen: false,
        height: 400,
       width: 350,
        modal: true,
        buttons: [
            {text: "提交", click: function () {
                    form.submit();
                }},
            {text: "取消", click: function () {
                    dialog.dialog('close');
                }
            }
        ],
        open: function() {
            form[ 0 ].reset();
            allFields.removeClass( "ui-state-error" );
            tips_msg && tips.text(tips_msg);
        }
    });

    form = dialog.find("form").on("submit", function(event) {
        event.preventDefault();  // 阻止默認(rèn)操作,需要提交到后端的時候注釋掉這句
        return addUser();  // 返回驗證的結(jié)果,如果為false,會阻止submit提交
    });

    $("#create-user").button().on("click", function() {
        dialog.dialog( "open" );
    });
})
</script>
</body>
</html>

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

網(wǎng)站題目:jQueryUI模態(tài)表單瘋狂踩坑-創(chuàng)新互聯(lián)
文章網(wǎng)址:http://www.muchs.cn/article14/diejge.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管關(guān)鍵詞優(yōu)化、品牌網(wǎng)站制作微信小程序、企業(yè)網(wǎng)站制作、響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)