jQuery 綁定事件

jQuery 綁定事件html

事件1:jquery

// 鼠標點擊出發事件
$('#id').click()

// * 委託、外部建立新的標籤,自動將id標籤下的a標籤作綁定事件
$('#id').delegate('a','click',functon (){
})
$('#id').undelegate('a','click',functon (){
})

$('#id').bind('click',functon (){
})

$('#id').unbind('click',functon (){
})

$('#id').on('click',functon (){
})

$('#id').off('click',functon (){
})
其餘

 

事件2:框架

:a標籤與onclick事件執行 自定義事件優先級高。ide

阻止事件發生:this

$('#id').click(function (){
alert(xxx);
   // 阻止後續事件發生
    return false;
    // 容許後續事件發生
    return true;
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--添加提交表單跳轉文件-->
<form action="s5.html" method="POST">
    <input type="text"/>
    <input type="submit" value="提交"/>
</form>

<script src="jquery-1.12.4.js"></script>
<script>
    $(':submit').click(function () {
        var v = $(this).prev().val();
        // 判斷input內容是否爲空
        if (v.length > 0) {
            // 不爲空容許後續事件執行
            return true;
        } else {
            alert('請輸出內容');
            // 終端後續發生事件
            return false
        }
    });
</script>
</body>
</html>
示例:簡單表單驗證處理

 

事件3:spa

頁面加載完畢自動執行:code

// 當頁面框架加載完畢以後,自動執行
$(function(){
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        /*添加樣式*/
        .error {
            color: red;
        }
    </style>
</head>
<body>
<!--添加提交表單跳轉文件-->
<form id='f1' action="s5.html" method="POST">
    <div><input name="n1" type="text"/></div>
    <div><input name="n2" type="password"/></div>
    <div><input name="n3" type="text"/></div>
    <div><input name="n4" type="text"/></div>
    <div><input name="n5" type="text"/></div>

    <!--提交按鈕-->
    <input type="submit" value="提交"/>
</form>

<script src="jquery-1.12.4.js"></script>
<script>
    // 當頁面框架加載完畢以後,自動執行
    $(function () {
        // 按鈕觸發事件
        $(':submit').click(function () {
            // 刪除.error樣式的標籤
            $('.error').remove();
            // 設置值
            var flag = true;
            // 取出input下的相應內容,並循環
            $('#f1').find('input[type="text"],input[type="password"]').each(function () {
                // 取出input內容下面內容
                var v = $(this).val();
                // 判斷input內容是否爲0
                if (v.length <= 0) {
                    // 若是爲0設置false
                    flag = false;
                    // 建立span標籤
                    var tag = document.createElement('span');
                    // 添加樣式
                    tag.className = 'error';
                    // 添加內容
                    tag.innerHTML = " * 必填";
                    // 添加span標籤到指定下個一位置
                    $(this).after(tag);
                    // return false;
                }
            });
            return flag;
        });
    });
</script>
</body>
</html>
示例:表單驗證、多輸入框判斷
相關文章
相關標籤/搜索