0
点赞
收藏
分享

微信扫一扫

jquery 绑定click事件

仅供学习,转载请注明出处


jquery 绑定click事件_click事件


绑定click事件

给元素绑定click事件,可以用如下方法:

$('#btn1').click(function(){

// 内部的this指的是原生对象

// 使用jquery对象用 $(this)

})

获取元素的索引值

有时候需要获得匹配元素相对于其同胞元素的索引位置,此时可以用index()方法获取

var $li = $('.list li').eq(1);
alert($li.index()); // 弹出1
......
<ul class="list">
<li>1</li>
<li>2</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>

选项卡示例

通过​​index()​​方法可以得到点击事件的元素序号,那么就可以根据该序号进行关联处理其他元素。


jquery 绑定click事件_html_02

jquery 绑定click事件_选项卡_03


点击上方不同的选项卡按钮,那么下方就会切换不同的div显示内容。
整体代码如下:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('.btns input').click(function(){

$(this).addClass('current').siblings().removeClass('current');

// alert($(this).index());
$(".cons div").eq($(this).index()).addClass('active').siblings().removeClass('active');
})

})
</script>
<style type="text/css">
.btns{
font-size: 0px;
}

.btns input{
border: 0px;
}

.current{
background-color: gold;
}

.cons div{
width: 300px;
height: 300px;
background-color: gold;
line-height: 300px;
text-align: center;
display: none;
}

.cons .active{
display: block;
}

</style>
</head>
<body>
<div class="btns">
<input type="button" name="" value="选项卡一" class="current">
<input type="button" name="" value="选项卡二">
<input type="button" name="" value="选项卡三">
</div>

<div class="cons">
<div class="active">选项卡一的内容</div>
<div>选项卡二的内容</div>
<div>选项卡三的内容</div>
</div>

</body>
</html>

这个​​click​​​事件里面的​​$(this)​​​很重要,用于设置被点击的按钮,然后再通过​​$(this).index()​​​来获取被点击的按钮序号。
从而让下面的​​​div.eq()​​函数得到对应的下标进行样式变更。


jquery 绑定click事件_html_04


举报

相关推荐

0 条评论