如何在悬停时向网页上的文字添加弹出(工具提示)定义?

Zac*_*ryC 4 javascript jquery tooltip

我的250页网站有一个词汇表,包含许多单词及其定义.我希望找到一种方法,使词汇表中的单词在网站文本中出现时突出显示,并显示"工具提示"气泡,显示单词在悬停时的定义.我的网页都是html - 我没有使用CMS.

我想我需要使用javascript.我已经查看并查找并找到了可以突出某些文本的javascript函数(即将其包装在span标签中),但我不知道如何让它迭代一系列单词并包含它们的定义,而且我'我不确定这将是多少资源密集型.

是否存在适用于我的词汇表类型程序,而无需在整个网站中手动更新每个单词的每个实例?或者有一种相当直接的方法来实现这一目标吗?谢谢!

Bra*_*sen 5

这可以使用JQuery完成,并且词汇表是页面上的隐藏div,如果需要,可以使用AJAX加载.

$("#glossary h2").each(function(index) {
  // Get the word and its definition.
  var word = $(this).text();
  var def = $("#glossary").find("p")[index].innerHTML;

  // Update all instances of that word in the content page with mouse over def.
  var contentHTML = $("#content").html();
  contentHTML = contentHTML.replace(new RegExp(word, 'g'), '<span title="' + def + '">' + word + '</span>');
  $("#content").html(contentHTML);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="content">
  Will likes to hang out with Jim.
</div>

<div id="glossary" style="display:none;">
  <h2>Will</h2>
  <p>This is will's def.</p>
  <h2>Jim</h2>
  <p>This is jim's def.</p>
</div>
Run Code Online (Sandbox Code Playgroud)

上面的函数假设您有一个单独的<p>,<h2>并且所有内容<p>都是定义的一部分.