事件:
1.页面载入
ready(fn);
#当文档准备完毕时
#当文档加载完毕时(onload)
当文档准备完毕时
$(document).ready(function(){
$(document).on('click','.close',function(){
$(this).parent().hide();
});
$('#comment').click(function(){
val=$('#txt').val();
str="<div class='comment'>";
str+="<h1>"+val+"</h1>";
str+="<div class='close'>×</div>";
str+='</div>';
$('#txt').val('');
$('body').append(str);
});
});
**
**
2.事件处理
bind();
#$(’.close’).on(‘click’,function(){
//代码
});
unbind();
#$(’.close’).off(‘click’);
one();
bind方法
$('img').bind('click',function(){
this.src='/img/fa.png';
});
bind和unbind加事件和取事件
<body>
<img src="/img/cai.png" alt="">
<br>
<button>加事件</button>
<button>取事件</button>
</body>
<script>
$('button').eq(0).click(function(){
$('img').bind('click',function(){
this.src='/img/fa.png';
});
});
$('button').eq(1).click(function(){
$('img').unbind('click');
});
</script>
one绑定一次事件
<h1>1111111111</h1>
</body>
<script>
i=0;
$('h1').one('click',function(){
$(this).html(i);
i++;
})
bind和unbind模拟one事件
<h1>张龙来了!</h1>
</body>
<script>
$('h1').bind('click',function(){
$(this).html(0);
$(this).unbind('click');
});
点赞功能
i=0;
$('h1').bind('click',function(){
if(i<=0){
val=parseInt($(this).html())+1;
$(this).html(val);
}else{
alert('您已经点过赞啦!');
}
i++;
});
事件绑定在未来产生的元素身上不能存活
<style>
*{
font-family: 微软雅黑;
}
h1{
margin:0px;
padding:0px;
}
.comment{
cursor: pointer;
border:2px solid #ccc;
border-radius:5px;
box-shadow:5px 5px 5px #000;
margin-bottom:15px;
position: relative;
}
.close{
position: absolute;
right:0px;
top:0px;
width:30px;
height:30px;
background: #ccc;
text-align: center;
line-height: 30px;
font-size:30px;
font-weight:bold;
}
#txt{
width:600px;
height:100px;
resize:none;
border-radius:5px;
padding:15px;
font-size:20px;
font-weight: bold;
}
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<h1>用户评论:</h1>
<hr>
<form action="">
<textarea id='txt'></textarea>
<br>
<input type="button" value="评论" id='comment'>
</form>
<hr>
<div class='comment'>
<h1>aaaaaaaaaaaaaaaaaaaaa</h1>
<div class="close">×</div>
</div>
</body>
<script>
$('.close').click(function(){
$(this).parent().hide();
});
$('#comment').click(function(){
val=$('#txt').val();
str="<div class='comment'>";
str+="<h1>"+val+"</h1>";
str+="<div class='close'>×</div>";
str+='</div>';
$('#txt').val('');
$('body').append(str);
$('.close').click(function(){
$(this).parent().hide();
});
});
</script>
3.事件委派
live();
#$(document).on(‘click’,’.close’,function(){
//代码
});
die();
#$(document).off(‘click’,’.close’);
**
**
**
**
4.事件切换
hover();
mouseenter鼠标移入,事件mouseleave鼠标离开事件
<body>
<img src="/img/cai.png" alt="">
</body>
<script>
$('img').mouseenter(function(){
$(this).attr({'src':'/img/fa.png'});
});
$('img').mouseleave(function(){
$(this).attr({'src':'/img/cai.png'});
});
</script>
hover鼠标移入和移出事件
$('img').hover(function(){
this.src='/img/fa.png';
},
function(){
this.src='/img/cai.png';
}
);
**
**
5.事件类型
obj.οnclick=function(){};
obj.click(function(){});
**
**