如何减少图像映射的此jquery切换代码

时间:2015-03-10 06:06:20

标签: javascript jquery html

我正在试图弄清楚如何减少此代码!它基本上隐藏了一个图像,然后根据点击的图像地图区域显示div!

我在这里有一个工作演示的代码笔:http://codepen.io/naniio/pen/wBExYq

$(document).ready(function() {
    $(".auckland").click(function() {
        $(".map").toggle();
        $("#aukl.hide").toggle();
    });

    $(".gisborne").click(function() {
        $(".map").toggle();
        $("#gisb.hide").toggle();
    });

    $(".wellington").click(function() {
        $(".map").toggle();
        $("#well.hide").toggle();
    });

    $(".nelson").click(function() {
        $(".map").toggle();
        $("#nel.hide").toggle();
    });

    $(".christchurch").click(function() {
        $(".map").toggle();
        $("#chch.hide").toggle();
    });

    $(".queenstown").click(function() {
        $(".map").toggle();
        $("#queen.hide").toggle();
    });

    $(".otago").click(function() {
        $(".map").toggle();
        $("#ota.hide").toggle();
    });
});

我尝试使用find和其他jquery方法,但我必须在错误的地方寻找

任何帮助都会很棒我是jQuery的新手但不是新的堆栈溢出我可以想象这对于某些人来说是一个简单的问题/修复,这可能会被严厉评价或被忽略!但对于那些不断帮助这个社区的人,谢谢! :)

5 个答案:

答案 0 :(得分:1)

<area>标签进行一些重构,例如

<area shape="circle" coords="220,97,15" alt="Auckland" title="Auckland" href="#" data-ref="aukl.hide">

会从不必要的类中清除你的html,并会给你更清晰的javascript代码:

$(document).ready(function() {
    $("map area").click(function() {
        $(".map").toggle();
        $("#" + this.data("ref")).toggle();
    });
});

答案 1 :(得分:1)

我在这支钢笔上工作。 http://codepen.io/anon/pen/ByOEam 只需在区域标签

中添加额外的属性即可
$(document).ready(function() {
    $(".clickable").click(function() {
       var toHide = $(this).attr('data-hide');
        $(".map").toggle();
        $("#"+toHide).toggle();
    });

    $(".hide").click(function() {
      $(".map").toggle();
      $(this).toggle();
    });


});

答案 2 :(得分:0)

将类添加到将被单击的所有div,例如“lands”,并使用以下代码,

$(".lands").click(function() {
    var $this = $(this);
    $(".map").toggle();
    $this.toggle();
});

答案 3 :(得分:0)

尝试使用此缩减的jquery代码

$(document).ready(function() {
  $('.box').on('click',function(){
      $(".map").toggle();
      $(this).toggle();
  });
});

答案 4 :(得分:0)

每当你需要为许多不同的对象添加相同的行为时,一个好的模式就是使用一个函数和动态创建。

例如,在您的具体情况下,我希望有

  • 带有地图的图像(无点)
  • 位置列表(可能从数据库中检索)
  • 每个位置的代码都会在地图上正确定位点图像

类似的东西:

function addLocation(x, y, name, data) {
    var dot = document.createElement("img");
    dot.className = "dot";
    dot.onload = function() {
        // x,y coordinates are relative to map size to account
        // for responsive designs
        dot.left = (x*mapContainer.offsetWidth - dot.offsetWidth/2) + "px";
        dot.top = (y*mapContainer.offsetHeight - dot.offsetHeight/2) + "px";
        mapContainer.appendChild(dot);
    };
    dot.src = "dot.png";
    dot.onclick = function() {
        showMap(name, data);
    };
}

这样添加/更改位置只需更新数据库(如果目前不值得使用数据库,则需要更新静态数据数组)。

手工添加位置名称和图表名称(这是随机的小变体之一,如gisborne->gisbchristchurch->chch)是使页面成为维护噩梦的一步。

相关问题