2015-09-27 90 views
1

当前我有悬停和单击事件的单独函数,但图标列表正在增加,我想使所有图标都可以使用的通用函数,但我不确定从何处开始。顺便说一句,我知道我使用反铲和挖掘机src相同的图像。创建jQuery函数以减少代码

var excavator = false; 
var backhoe = false; 
var paver = false; 
var compactor = false; 
var motorgrator = false; 


$("#excavator").mouseleave(function() { 
    if(!excavator) 
     $(this).attr("src", "img/default_excavator.png"); 
}); 
$("#excavator").mouseenter(
    function() { 
     if(!excavator) 
     $(this).attr("src", "img/hover_excavator.png"); 
}); 
$("#excavator").click(
    function() { 
    $(this).attr("src", "img/active_excavator.png"); 
    $("#equipmentList").load('partials/excavator.php'); 
    excavator = true; 
    backhoe = false; 
    $("#backhoe").attr("src", "img/default_excavator.png"); 
}); 

/******************** end of excavator ********************/ 

$("#backhoe").mouseleave(function() { 
    if(!backhoe) 
     $(this).attr("src", "img/default_excavator.png"); 
}); 
$("#backhoe").mouseenter(
    function() { 
     if(!backhoe) 
     $(this).attr("src", "img/hover_excavator.png"); 
}); 
$("#backhoe").click(
    function() { 
    $(this).attr("src", "img/active_excavator.png"); 
    $("#equipmentList").load('partials/backhoe.php'); 
    backhoe = true; 
    excavator = false; 
    $("#excavator").attr("src", "img/default_excavator.png"); 
}); 

$('#top').click(function(){ 
    $("html, body").animate({ scrollTop: 0 }, 600); 
    return false; 
}); 
下面

是部分从HTML

<div class="container"> 
     <div class="row-fluid"> 
      <div class="col-lg-12"> 
       <h3>Equipments</h3> 
       <div id="equipmentSelection" class="block-inline" style="margin-bottom: 1%"> 
        <img id="excavator" src="img/default_excavator.png" alt=""/> 
        <img id="backhoe" src="img/default_excavator.png" alt=""/> 
       </div> 
       <div class="panel panel-default"> 
        <div id="equipmentList" class="panel-body"> 
        <h4>Select above to browse our equipments</h4> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
+0

唐真的不懂逻辑......为什么你必须先点击图片,然后才能将鼠标悬停在图片的源代码中? – charlietfl

+0

我有三个图像为每个按钮,一个表示悬停,一个默认状态,第三个表示按钮是否被点击,因为点击后它会显示与该按钮相关的数据 –

+0

很容易添加一个类到点击并在你的答案第一行改变它的风格与该类 – charlietfl

回答

0

绑定的功能,以通用的容器类,并检查你函数在当前元素的ID内:

$(".container .row-fluid .col-lg-12 img").mouseleave(function() { 
    if ($(this).attr('id') == 'excavator') 
    { 
     // DO SOMETHING HERE 
    } 

    if ($(this).attr('id') == 'backhoe') 
    { 
     // DO SOMETHING ELSE HERE 
    } 
}); 
+0

我可以用$(“#equipmentSelection”)替换。mouseleve?因为所有图标/按钮都在设备选择ID的那个div内。 –

+0

是的,你可以,但在这种情况下,你不会知道哪个IMG被悬停 –

+0

好吧,谢谢让我试试看 –