javascript - 我如何扩展此 JavaScript 以适用于多个项目?

标签 javascript html

我找到了一个解决方案,它允许我单击某个区域以使用 JavaScript 显示工具提示,但仅适用于第一项。 Here is that solution.

这是代码:

<script>
  function doTip(e) {
    var elem = e.toElement;
    if (elem.getAttribute('data-tip-on') === 'false') {

      elem.setAttribute('data-tip-on', 'true');
      var rect = elem.getBoundingClientRect();
      var tipId = Math.random().toString(36).substring(7);
      elem.setAttribute('data-tip-id', tipId);
      var tip = document.createElement("div");
      tip.setAttribute('id', tipId);
      tip.innerHTML = elem.getAttribute('data-tip');
      tip.style.top = event.clientY + 15 + 'px';
      tip.style.left = event.clientX + 10 + 'px';
      tip.setAttribute('class', 'tip-box');
      document.body.appendChild(tip);

    } else {

      elem.setAttribute('data-tip-on', 'false');
      var tip = document.getElementById(elem.getAttribute('data-tip-id'));
      tip.parentNode.removeChild(tip);


    }
  }

  function enableTips() {
    var elems = document.getElementsByClassName('quick-tip');
    for (var i = 0; i < elems.length; i++) {
      elems[0].addEventListener("click", doTip, false);

    }
  }
  window.onload = function() {
    enableTips();
  }

</script>
<style>
  .quick-tip {
    background: black;
    color: #fff;
    padding: 5px;
    cursor: pointer;
    height: 15px;
    width: 15px;
    text-align: center;
    font-weight: 900;
    margin-left: 350px;
  }

  .tip-box {
    /* change dimensions to be whatever the background image is */
    height: 50px;
    width: 200px;
    position: absolute;
  }

</style>

<map>
  <area class="quick-tip" shape="poly" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false"/>

  <area class="quick-tip" shape="poly" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false"/>
</map>

<script>
  enableTips();

</script>  

只有最上面的一个起作用,下面的什么都不做。我需要的功能是两个按钮在单击时显示工具提示。我尝试过缝合不同解决方案的其他部分,但无济于事。我也尝试过其他解决方案,但似乎都不适用于我的页面。

我修改了原来的解决方案并使用 <area>因为页面原本是鼠标悬停在<area>上时弹出工具提示的。 。悬停功能需要更改为单击,如解决方案中所示,但第一个是唯一有效的。

最佳答案

你有一个错别字

elems[0].addEventListener("click", doTip, false);

应该是

elems[i].addEventListener("click", doTip, false);

关于javascript - 我如何扩展此 JavaScript 以适用于多个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49806311/

相关文章:

javascript - 如何为 ajax 成功发送两个或多个单独的结果

javascript - 单击 "Submit"按钮获取值时访问元素

html - 在 Twig 中的表单中获取 css ID 的名称

javascript - Google Analytics 中的 iOS 电话超链接 javascript 跟踪

javascript - 谷歌地图捏缩放事件

html - 如何在 HTML/Angular 中为数字设置 ng-pattern

javascript - Bootstrap 3 - 将鼠标悬停在另一个表中的特定行上时突出显示表行

javascript - 如何使用类之类的东西将 onclick 代码移动到一个地方。在各种 html 标签处重复代码

javascript - 在悬停jquery上从右向左滑动div

javascript - jQuery 单击功能不适用于 ID