05-jquery 绑定click事件
给元素绑定click事件,可以用如下方法:
$('#btn1').click(function(){
//内部的this指的是原生对象
//使用jquery对象用$(this)
})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>绑定click事件</title> <script src="js/jquery.js"></script> <script> $(function(){ //给#btn绑定click事件 $("#btn").click(function(){ /* //如果class为.box的元素同时有col01的class if($('.box').hasClass('col01')){ //去掉class:col01 $(".box").removeClass("col01") } else{ //添加class:col01 $('.box').addClass('col01') } 这个if else实现的切换css样式可以简化成下面的写法 */ //toggleClass的功能是检查所选元素有没有col01的class,没有就添加,有就去掉 $('.box').toggleClass('col01'); }) }) </script> <style> .box{ width:200px; height:200px; background-color:gold; } .col01{ background-color:green; } </style> </head> <body> <input type="button" value="切换样式" id="btn"> <div class="box">div element</div> </body> </html>

浙公网安备 33010602011771号