创建jQuery函数以减少代码

时间:2015-09-27 18:46:04

标签: jquery

目前我有悬停和点击事件的单独功能,但图标列表正在增长,我想制作可以使用所有图标的通用功能,但我不知道从哪里开始。顺便说一下,我知道我在反铲挖掘机和挖掘机src上使用相同的图像。

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>

1 个答案:

答案 0 :(得分:0)

将您的函数绑定到通用容器类,并在函数内部检查当前元素的id:

row