有什么方法可以比较2个不同数组的索引号吗?
这就是我想要做的:
if i[0] == k[0] {
//give some action to k[0]
} else if i[1] == k[1] {
// give some action to k[1]
}
...等等。
我本可以使每个函数0到4来解决我的问题,但是那样的话,代码太长且不可读。我想尽可能地优化代码。
我写了这样的代码,但这对我想要的不起作用。当我将鼠标悬停在其中一个框组上时,所有k
都会保持动作。
这是我的代码:
var i = $('#boxgroup').children()
var k = $('#panelgroup').children()
$(i).each(function() {
$(this).hover(function() {
if($(i == k)){
$(k).stop().animate({height: '500px'})}
}, function(){
$(k).stop().animate({height: '200px'})
})
})
#boxgroup{
width: 600px;
height: 200px;
border: 1px solid black;
clear: both;
}
.box {
width: 200px;
height: 50px;
border: 1px solid black;
float: left;
position: relative;
top: 0px;
margin: 10px;
}
.panelgroup {
clear: both;
}
.panel {
width: 200px;
height: 200px;
border: 1px solid gray;
top: 400px;
float: left;
}
<div id="boxgroup">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>
<br>
<div id="panelgroup">
<div class="panel">panel1</div>
<div class="panel">panel2</div>
<div class="panel">panel3</div>
<div class="panel">panel4</div>
</div>
答案 0 :(得分:3)
听起来您想将鼠标悬停在#boxgroup
中的一个孩子上,以使#panelgroup
中的同一个孩子更大。如果是这样,则不需要一系列的if
,只需要元素的索引即可:
$('#boxgroup > *').hover(
function() {
var index = $(this).index(); // Returns its index within boxgroup
$("#panelgroup > *:eq(" + index + ")").stop().animate({height: '500px'});
},
function() {
var index = $(this).index(); // Returns its index within boxgroup
$("#panelgroup > *:eq(" + index + ")").stop().animate({height: '200px'});
}
);
实时示例:
$('#boxgroup > *').hover(
function() {
var index = $(this).index(); // Returns its index within boxgroup
$("#panelgroup > *:eq(" + index + ")").stop().animate({height: '500px'});
},
function() {
var index = $(this).index(); // Returns its index within boxgroup
$("#panelgroup > *:eq(" + index + ")").stop().animate({height: '200px'});
}
);
#boxgroup{
width: 600px;
height: 200px;
border: 1px solid black;
clear: both;
}
.box {
width: 200px;
height: 50px;
border: 1px solid black;
float: left;
position: relative;
top: 0px;
margin: 10px;
}
.panelgroup {
clear: both;
}
.panel {
width: 200px;
height: 200px;
border: 1px solid gray;
top: 400px;
float: left;
}
<div id="boxgroup">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>
<br>
<div id="panelgroup">
<div class="panel">panel1</div>
<div class="panel">panel2</div>
<div class="panel">panel3</div>
<div class="panel">panel4</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
请参阅: