javascript - 如何将 HTML id 存储为 js 变量?

标签 javascript html variables getelementbyid onmouseover

我正在编写一个每页将有 200 多个链接的网页。每个链接都有一个唯一的 ID,与另一个框架中的 ID 相匹配。我想运行一个 onmouseover 函数,它将跨框架更改两个链接的文本颜色。这是我到目前为止所得到的。

<html><head><title>Test</title>
  <script>
    function hey()
      {var id=//HELP PLEASE; document.getElementById(id).style.color = "red";} 
    function bye()
      {var id=//HELP PLEASE; document.getElementById(id).style.color = "black";}
  </script>
 </head>
<body>
 <a id="1" class="word" onmouseover="hey()" onmouseout="bye()">hello</a> 
 <a id="2" class="word" onmouseover="hey()" onmouseout="bye()">world</a>....
</body></html>

有什么想法吗?

最佳答案

将 id 传递给函数:

<html><head><title>Test</title>
  <script>
    function hey(id)
      {document.getElementById(id).style.color = "red";} 
    function bye(id)
      {document.getElementById(id).style.color = "black";}
  </script>
 </head>
<body>
 <a id="1" class="word" onmouseover="hey(this.id)" onmouseout="bye(this.id)">hello</a> 
 <a id="2" class="word" onmouseover="hey(this.id)" onmouseout="bye(this.id)">world</a>....
</body></html>

关于javascript - 如何将 HTML id 存储为 js 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14968108/

相关文章:

javascript - jQuery html() 与其他函数链接时序问题

javascript - jQuery 弹出/叠加效果

html - 是否可以仅使用 CSS 修改父节点子节点(包括原始节点的悬停)的外观?

html - 将 div 缩小到内容大小

java - 在for循环中声明变量的优点和缺点?

javascript - 如何在 IE 中打印横向多页?

javascript - 通过按索引将对象推送到数组来对数组进行排序

javascript - webpack 热模块替换不起作用

javascript - 将用户输入的 javascript 变量写入文档

sql - 在 sql (hive) 中声明变量