一,jQuery事件机制
(1)、注册事件
bind()、on()方法向被选元素添加一个或多个事件处理程序,以及当事件发生时运行
的函数。
$("#header1").bind({
mouseover(){
$(this).css("background-color","blue");
},
mouseout(){
$(this).css("background-color","black");
}
})
$("p").on("click",function(){alert("段落被点击了。");});
(2)、委托事件
delegate()方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,
并规定当这些事件发生时运行的函数
$("div").delegate("p","click",function(){
$("p").css("background-color","pink");
});
(3)、事件对象event
event对象有以下属性
type:事件类型,比如click。
which:触发该事件的鼠标按钮或键盘的键。
target:事件发生的初始对象。
data:传入事件对象的数据。
pageX:事件发生时,鼠标位置的水平坐标(相对于页面左上角)。
pageY:事件发生时,鼠标位置的垂直坐标(相对于页面左上角。
(4)、each()方法
each()方法为每个匹配元素规定要运行的函数。
$("button").click(function(){
$("li").each(function(){
alert($(this).text())
});
});
(5)、jQuery.each()函数用于遍历指定的对象和数组。
//$.each(数组或对象,回调函数)
vararr=[10,20,30,40];
$.each(arr,function(index,value){
console.log(`我是第${index+1}元素,值是${value}`);
})