jQuery event handling and event unbinding

jQuery event handling and event unbinding

  1. Bind a single event
		//css代码      
        div{
	        width: 200px;
	        height: 200px;
	        background-color: teal;
        }
        //html代码
        <div></div>
        //方法1
        //jQuery代码(记得引入jQuery文件)
        $(function() {
            $('div').click(function() {
                alert('你点我了');
            })
        })
        //方法2
       $('div').on('click', function() {
             alert('你点我了');
       })
  1. Bind multiple events
        //jQuery代码(记得引入jQuery文件)
        $(function() {
            $('div').on({
                mouseenter: function() {
                    $('div').css('backgroundColor', 'pink');
                },//鼠标进去背景颜色改为pink
                mouseleave: function() {
                    $('div').css('backgroundColor', 'blue');
                },//鼠标离开背景颜色改为blue
                click: function() {
                    $('div').css('backgroundColor', 'red');
                }//鼠标点击背景颜色改为red
            })
        })

If the bound events are the same, you can use the convenient way

		//css代码
		.current {
            width: 100px;
            height: 100px;
            background-color: yellow;
        }
        //jQuery代码(记得引入jQuery文件)
        $(function() {
            $('div').on('mouseenter mouseleave', function() {//多个事件处理程序之间用空格分开
                $('div').toggleClass('current');
            })
        })
  1. Unbind event $('div').off()
//jQuery代码(记得引入jQuery文件)
$('div').off(); //解绑所有事件
$('div').off('click'); //解绑onclick事件
  1. The difference between one() and on()
    one(), as the name suggests, can only be triggered once, while on() can start countless times
//jQuery代码(记得引入jQuery文件)
$('div').one(function(){
	alert('我只能弹出来一次');//这个对话框只能弹出来一次
})
$('div').on('click',function(){
	alert('我能弹出无数次'); //每点击一次弹出对话框一次
})

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110713075