欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

jquery阻止默认行为_jQuery中的事件处理(阻止事件冒泡、阻止默认行为) 有大用 有大大用

1.冒泡事件:

举例:点击div元素,body元素也会执行点击事件,从而修改了body背景,但是我们指向修改div的背景

//jQuery function 入口

$(document).ready(function(){//body元素添加点击事件

$("body").bind("click",function(){//修改背景颜色

$(this).css("background-color","yellow")

})//div元素添加点击事件

$("div").bind("click",function(){//修改背景颜色

$(this).css("background-color","red")

})

})

输出:

2.阻止事件冒泡

方法1:

event.stopPropagation() 方法

语法:

event.stopPropagation()

示例:

//jQuery function 入口

$(document).ready(function(){//body元素添加点击事件

$("body").bind("click",function(){//修改背景颜色

$(this).css("background-color","yellow")

})//div元素添加点击事件

$("div").bind("click",function(e){//修改背景颜色

$(this).css("background-color","red")//阻止冒泡

e.stopPropagation()

})

})

输出:

方法2:

return false

示例:

//jQuery function 入口

$(document).ready(function(){//body元素添加点击事件

$("body").bind("click",function(){//修改背景颜色

$(this).css("background-color","yellow")

})//div元素添加点击事件

$("div").bind("click",function(e){//修改背景颜色

$(this).css("background-color","red")//阻止冒泡

return false})

})

3.默认行为

示例:点击标签,不管点击是还是否,都会默认跳转页面

跳转

//jQuery function 入口

$(document).ready(function(){//body元素添加点击事件

$("body").bind("click",function(){//修改背景颜色

$(this).css("background-color","yellow")

})//div元素添加点击事件

$("div").bind("click",function(e){//修改背景颜色

$(this).css("background-color","red")//阻止冒泡

return false})

$("a").bind("click",function(e){var d = window.confirm("您访问的网址存在安全风险,是否继续")

})

})

输出:都会跳入“#”

4.阻止默认行为:

方法1:

event.preventDefault() 方法阻止元素发生默认的行为。

语法:

event.preventDefault()

示例:

跳转

//jQuery function 入口

$(document).ready(function(){//body元素添加点击事件

$("body").bind("click",function(){//修改背景颜色

$(this).css("background-color","yellow")

})//div元素添加点击事件

$("div").bind("click",function(e){//修改背景颜色

$(this).css("background-color","red")//阻止冒泡

return false})

$("a").bind("click",function(e){//阻止冒泡

e.stopPropagation()var d = window.confirm("您访问的网址存在安全风险,是否继续")if(d==false){//阻止默认行为

e.stopPropagation()

}

})

})

输出: 点击否,就不会跳转

方法2:

return false

示例:

跳转

//jQuery function 入口

$(document).ready(function(){//body元素添加点击事件

$("body").bind("click",function(){//修改背景颜色

$(this).css("background-color","yellow")

})//div元素添加点击事件

$("div").bind("click",function(e){//修改背景颜色

$(this).css("background-color","red")//阻止冒泡

return false})

$("a").bind("click",function(e){//阻止冒泡

e.stopPropagation()var d = window.confirm("您访问的网址存在安全风险,是否继续")if(d==false){return false}

})

})

总结:

return false 即阻止冒泡,又阻止默认行为

普通分类: