javascript - 如何获取调用函数的id?

标签 javascript html css area

我正在尝试做一个函数,当标签区域中的不同 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>

最佳答案

按如下方式更改您的函数定义:

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

然后,用法如下:

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

当以这种方式调用 Over 方法时,它会将当前 HTML 元素作为参数传递。

关于javascript - 如何获取调用函数的id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931907/

相关文章:

javascript - 使用 JavaScript 打开 ModalPopupExtender

javascript - 一次选择一个单选按钮

html - 我可以在音频源标签上设置一个(有效的)空 src 吗?

html - 行内 block 元素不对齐

javascript - Heroku "Invalid Host header"HOST 配置中的 ReactJS APP?

javascript - 绘制原型(prototype)链

jquery - 当我将鼠标悬停在另一个 div 上时平滑 div 的淡入

javascript - 在html中显示来自nodejs的数据

javascript - 防止从 javascript 打印网站 url

html - CSS 属性裁剪颜色背景