2017-03-21 78 views
0

我正试图做一个功能,显示不同的东西时,在标签区域中由不同的ID调用。如何获取调用函数的ID?

我读过的答案类似的要求,但我无法弄清楚我的错误。

function Over() { 
 
     if (this.id == "cc") { 
 
      el = document.getElementById("Box1") 
 
      el.style.display = 'block'; 
 
     } else if (this.id == "mm") { 
 
      el = document.getElementById("Box2") 
 
      el.style.display = 'block'; 
 
     } else if (this.id == "ca") { 
 
      el = document.getElementById("Box3") 
 
      el.style.display = 'block'; 
 
     } 
 
    } 
 

 
    function Out() { 
 
     if (this.id == "cc") { 
 
      el = document.getElementById("Box1") 
 
      el.style.display = 'none'; 
 
     } else if (this.id == "mm") { 
 
      el = document.getElementById("Box2") 
 
      el.style.display = 'none'; 
 
     } else if (this.id == "ca") { 
 
      el = document.getElementById("Box3") 
 
      el.style.display = 'none'; 
 
     } 
 
    }
#Box1, #Box2, #Box3 { 
 
    display: none; 
 
    top: 250px; 
 
    width: 20%; 
 
    height: 100px; 
 
    background-color: red; 
 
    margin-left: 38%; 
 
    position: absolute; 
 
    border: solid; 
 
    border-color: black; 
 
    z-index: 100; 
 
    border-radius: 10px; 
 
    -moz-border-radius: 10px; 
 
    /* firefox */ 
 
    -webkit-border-radius: 10px; 
 
    /* safari, chrome */ 
 
    text-align: center; 
 
} 
 

 
#Box2 { 
 
    top: 450px; 
 
    width: 10%; 
 
    height: 100px; 
 
    background-color: green; 
 
    margin-left: 18%; 
 
} 
 

 
#Box3 { 
 
    top: 50px; 
 
    width: 3%; 
 
    height: 50px; 
 
    background-color: yellow; 
 
    margin-left: 0; 
 
}
<img src="ticinello2.jpg" id="imgmap" alt="Mappa" usemap="#parkmap"> 
 
<map name="parkmap" id="map"> 
 
    <area shape="poly" coords="326,196,321,370,424,283,426,197" target="_blank" alt="polycc" href="#" onmouseover=Over.call(this) onmouseout="Out.call(this)" id="cc" /> 
 
    <area shape="poly" coords="426,198,554,458,457,553,328,404,324,404,324,375" target="_blank" alt="polymm" href="#" onmouseover=Over.call(this) onmouseout="Out.call(this)" id="mm" /> 
 
    <area shape="poly" coords="328,405,324,412,325,675,330,681,451,554" target="_blank" alt="polyca" id="ca" href="#" onmouseover="Over.call(this)" onmouseout="Out.call(this)" /> 
 
</map>

+2

你传递的参数'this'到功能('在()','出()')不带参数。给它们添加一个参数,使它们成为'function Over(e){...}'和'Out(e){...}'函数,然后通过执行'e.id'而不是'this .id'。 – Santi

+0

@Santi Or,甚至更好,将它们更改为'function Over(this){...}'。 – Feathercrown

+3

@Santi实际上,他没有传递'this',他使用'call',它改变函数内部的'this'属性。 – Feathercrown

回答

0

如下更改函数定义:

function Over(elm) { 
    // get id 
    var elementId = elm.id; 
} 

然后,用法如下:

<area .... id="cc" onclick="Over(this);" /> 

当调用Over方法这种方式,它是通过当前的HTML元素为论据。

+0

我试过了,似乎在我的情况下工作 –

+0

我错了,它的工作原理 –

相关问题