1. 程式人生 > 其它 >jQuery事件繫結學習筆記

jQuery事件繫結學習筆記

技術標籤:筆記

jQuery事件繫結學習筆記

1.jQuery點選事件

js中所有的功能的使用是以屬性為主,jQuery中是以函式為主

<body>

    <button>
        <strong>click to change div content</strong>
    </button>
    <div>今日頭條:</div>

    <script>
        //獲取一個button元素物件的集合
        let $btn = $('button');

        //下面是js繫結事件的形式,js中所有的事件都以on開頭
//$btn[0].onclick = function(){} //jQuery繫結點選事件,事件是呼叫函式的方式,注意函式名前不需要on開頭 //event 事件源(包含了該事件的所有資訊,只要有事件存在,該事件源物件就預設存在) $btn.click(function(event){ console.log($(this).text()) console.log($('div').text()); //event.target 屬性返回哪個 DOM 元素觸發了事件。 console.
log(event.target) });
</script> </body>

阻止事件冒泡:.stopPropagation()

需求:

​ 頁面中點選ul標籤,使其顯示或隱藏

<body>	 	 
        <div class="title">
            <h4>電子產品</h4>
            <ul style="display: none;" >
                <li>手機</
li
>
<li>手錶</li> </ul> </div> <script src="./js/jquery-3.1.1.js"></script> <script type="text/javascript"> //jQuery的事件繫結:會將所有的獲取到的元素都繫結事件(下面是標籤類名為"title的") $('.title').click(function(){ //繫結點選事件 //用js獲取當前元素中的第一個ul元素 let ulNode = this.getElementsByTagName('ul')[0]; //js物件轉為jQuery物件 let $ulNode =$(ulNode); //獲取到元素的display屬性值,點選時先判斷隱藏狀態,然後做隱藏或顯示的操作 if($ulNode.css('display') == "none"){ $ulNode.css('display','block'); }else{ $ulNode.css('display','none'); } }) </script> </body>

​ 這樣有一個問題,在ul標籤顯示後,點選其子標籤li也會呼叫ul的點選事件。因為元素之間是包裹關係,所以點選子元素,會向上查詢對應的父元素中是否有事件----也就是事件冒泡,可以用以下的方式解決:

<body>
    
    <div class="title">
        <h4>電子產品</h4>
		//標籤的點選事件中新增阻止事件冒泡的函式,點選子標籤就不會觸發父元素的點選事件了
        <ul style="display: none;" onclick="stop(event)"  >
            <li>手機</li>
            <li>手錶</li>
        </ul>
    </div>

    <script src="./js/jquery-3.1.1.js"></script>
    <script type="text/javascript">	
  
        $('.title').click(function(){
            let ulNode = this.getElementsByTagName('ul')[0];
            let $ulNode =$(ulNode);
            if($ulNode.css('display') == "none"){
                $ulNode.css('display','block');
            }else{
                $ulNode.css('display','none');
            }
        })


        function stop(e){
            //阻止事件冒泡
            e.stopPropagation();
        }
    </script>

</body>
2.jQuery改變事件
<body>
    <input type="text">
    <select name="" id="">
        <option value="">123</option>
        <option value="">456</option>
        <option value="">789</option>
    </select>

    <script src="./js/jquery-3.1.1.js"></script>
    <script>
        //jQuery變化事件呼叫.change()函式
        $('input').change(function(){
            //輸入框的值改變時就彈框顯示該值
            alert($(this).val());
        })
        $('select').change(function(){
            //下拉框的值改變時就彈框顯示該選項在下拉列表中的索引
            alert(this.selectedIndex);
        })
    </script>
</body>
3.jQuery表單提交事件
<body>
    <form action="" >
        使用者名稱:<input type="text" name="uname">
        密碼:<input type="password" name="pwd">
        <input type="submit" value="登入">
    </form>

    <script src="js/jquery-3.1.1.js"></script>
    <script type="text/javascript">

        //獲取form表單裡的input的內容(使用者名稱和密碼),也就是要提交的資料
        let $inNodes = $('input');

        //.submit(function(){}),繫結提交事件,function函式裡定義事件具體內容
        $('form').submit(function(){
            //獲取輸入的使用者名稱資料
            let unameVal = $inNodes.val();
            //如果使用者名稱為空,則函式返回false,表單不執行提交,否則提交表單資料
            if(unameVal==""){
                return false;
            }
            return true;
        })
    </script>
</body>
4.jQuery焦點事件
<body>

    <input type="" />
    <div id="" style="width: 100px;height: 100px;background-color: aqua;">
    </div>


    <script src="./js/jquery-3.1.1.js"></script>
    <script type="text/javascript">
        //焦點事件
        $('input').focus(function(){
            $(this).css("backgroundColor","darkcyan");
            $('div').css("backgroundColor","orange");
        })
        //失去焦點事件
        $('input').blur(function(){
            $(this).css("backgroundColor","cadetblue");
            $('div').css("backgroundColor","steelblue");
        })
    </script>
</body>
5.jQuery事件繫結–on

js中給後新增進來(通過js動態新增到頁面中的元素)的元素繫結事件是一件比較麻煩的事情,jQuery中可以用on事件處理

/*需求:點選按鈕在表格內新增一行元素,這行元素中的一個標籤有刪除該行的功能(點選事件) */
<body>
    <button>create Element</button>
    <hr>
    <table id="test" border="1" cellpadding="0" cellspacing="0" width="50%" align="center">
    </table>


    <script src="./js/jquery-3.1.1.js"></script>
    <script type="text/javascript">
        //button按鈕的點選事件繫結
        $('button').click(function(){
            //父元素.append(子元素) 給父元素新增子元素,每次都新增到父元素的末尾
            $('table').append("<tr><td>刪除</td></tr>");
        })

       /*頁面載入完時,td標籤並未建立,要等到手動點選建立,此事件繫結是無效的,因此不能這樣寫
       $('td').click(function(){
            //.parentNode 查詢父元素節點
            let trNode = this.parentNode;
            //.remove()移除該元素
            trNode.remove();
        })
        */

    </script>

</body>

可以用on事件繫結:

<body>
    <button>create Element</button>
    <hr>
    <table id="test" border="1" cellpadding="0" cellspacing="0" width="50%" align="center">
    </table>


    <script src="./js/jquery-3.1.1.js"></script>
    <script type="text/javascript">
        $('button').click(function(){
            //父元素.append(子元素) 給父元素新增子元素,每次都新增到父元素的末尾
            $('table').append("<tr><td>刪除</td></tr>");
        })

		//語法:$('父元素').on(事件名,選擇器,函式),給子元素新增事件
        $('table').on('click','td',function(){
                //.parentNode 查詢父元素節點
                let trNode = this.parentNode;
                //.remove()移除該元素
                trNode.remove();
        })
    </script>

</body>

on同時繫結多個事件

/*給input標籤新增焦點事件和失去焦點事件*/
//兩次事件繫結
$('input').blur(function(){
    var phone = $(this).val();
    var $span = $(this).next();
    if(phone.length!=11){

        $span.html('手機號錯誤')
        $span.css('color','red')
    }else{
        $span.html('')
    }
})
$('input').focus(function(){
    $(this).next().html('請輸入11位手機號');
    $(this).next().css('color','black')
})


//使用on同時繫結兩個事件
$('input').on({
    'blur':function(){
        var phone = $(this).val();
        var $span = $(this).next();
        if(phone.length!=11){

            $span.html('手機號錯誤')
            $span.css('color','red')
        }else{
            $span.html('')
        }
    },
    'focus':function(){
        $(this).next().html('請輸入11位手機號');
        $(this).next().css('color','black')
    }
})
6.jQuery事件繫結–ready

和onload事件相似,ready也是頁面載入完後再執行該事件中的程式碼

<head>
    
    <script src="./js/jquery-3.1.1.js"></script>
    <script>
        /*onload事件
        window.onload = function(){
            $('button').click(function(){
                alert("-----");
            })
        }
        window.onload = function(){
            $('button').click(function(){
                alert("*********");
            })
        }
		//onload 事件只能存在一次,多個會被覆蓋,且在DOM結構及圖片都載入完畢後才會執行函式中的程式碼
        */


        //ready事件是可以多次使用,ready事件是在DOM結構載入完畢後就執行
        $(function(){
            $('button').click(function(){
                alert("-----");
            })
        })
        $(function(){
            $('button').click(function(){
                alert("*********");
            })
        })
    </script>
    
</head>

<body>

    <button>click</button>

</body>

onload和ready的區別
1.onload只能使用一次,ready可以多次使用
2.執行時機不同(onload是在DOM結構及圖片資源載入完後執行,ready是在DOM結構載入完後執行)