jQuery使用.each()循环.hover()函数

时间:2015-02-27 00:59:56

标签: javascript jquery arrays each

我有一个更改箭头边框颜色的功能,以匹配按钮的悬停状态颜色。它作为3个单独的函数工作,但我想用.each()组合它们请告诉我我哪里出错了

enter image description here

瓦尔

var btnArrowPath = '.btn + .btn-arrow';
var btnName = ['btn-infra ','btn-dev ','btn-anal '];
var btnColor = ['#286090','#449d44','#31b0d5'];
var btnRollColor = ['#337ab7','#5cb85c','#5bc0de'];

功能

 $('.btn-wrap').each(function(i, value){
    $(btnName[value] + '.btn').hover(function(i, value){
      $(btnName[value] + btnArrowPath).css('border-top-color',btnColor[value]);
   }, function(){
      $(btnName[value] + btnArrowPath).css('border-top-color',btnRollColor[value]);
   });
 });

HTML

<div class="hero-wrap">
                <div class="hero-popup">
                    <div class="row">
                        <div class="btn-wrap btn-infra">
                            <button data-trigger="focus" type="button" class="btn btn-primary" data-toggle="popover" title="Infrastructure" data-content="And here's some amazing content. It's very engaging. Right? <a href='#'>Do it!</a>" data-placement="bottom">Infrastructure</button>
                            <div class="btn-arrow pull-right"></div>
                    </div>
                    </div>
                    <div class="row">
                        <div class="btn-wrap btn-dev">
                            <button data-trigger="focus" type="button" class="btn btn-info" data-toggle="popover" title="Development" data-content="And here's some amazing content. It's very engaging. Right? <a href='#'>Do it!</a>" data-placement="top">Development</button>
                            <div class="btn-arrow pull-right"></div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="btn-wrap btn-anal">
                            <button data-trigger="focus" type="button" class="btn btn-success" data-toggle="popover" title="Analysis" data-content="And here's some amazing content. It's very engaging. Right? <a href='#'>Do it!</a>" data-placement="top">Analysis</button>
                            <div class="btn-arrow pull-right"></div>
                    </div>
                </div>
            </div>]

1 个答案:

答案 0 :(得分:1)

您希望.btn元素中的.btn-wrap元素具有悬停功能,这将改变悬停元素的下一个兄弟的边框顶部颜色,不是吗?

所以

$('.btn-wrap .btn').each(function (i, value) {
    $(this).hover(function (e) {
        $(this).next('.btn-arrow').css('border-top-color', btnColor[i]);
    }, function () {
        $(this).next('.btn-arrow').css('border-top-color', btnRollColor[i]);
    });
});

演示:Fiddle


你可以在没有像

这样的循环的情况下完成
var $btns = $('.btn-wrap .btn').hover(function (e) {
    $(this).next('.btn-arrow').css('border-top-color', btnColor[$btns.index(this)]);
}, function () {
    $(this).next('.btn-arrow').css('border-top-color', btnRollColor[$btns.index(this)]);
});

演示:Fiddle