HTML [Show] 代码 添加 2 个时只显示其中 1 个?

标签 html show-hide

当我添加下面的代码时。

<a id="show_id" 
   onclick="document.getElementById('spoiler_id').style.display='';
            document.getElementById('show_id').style.display='none';"
   class="link">
   [Show]
</a>
<span id="spoiler_id" style="display: none">
  <a onclick="document.getElementById('spoiler_id').style.display='none';
              document.getElementById('show_id').style.display='';"
     class="link">
  [Hide]
  </a>
<br>
INSERT CONTENT HERE
</span>

当我将其中的 2 个代码放入 HTML 页面时,我只能让其中的 1 个代码真正起作用吗?对为什么这种情况不断发生有什么帮助吗?

干杯, 詹姆斯

最佳答案

添加第二个代码块是可行的,但您需要确保您使用的 id 对两个 block 都是不同的。假设区 block 1 的 ID 为 show_idspoiler_id,区 block 2 的 ID 也为 show_idspoiler_id,然后 document.getElementById(show_id) 将始终选择第一次出现的 show_id

<!--Code blocks. Note they both have the same IDs and getElementById-->
<!--Block 1-->
<a id="show_id" 
   onclick="document.getElementById('spoiler_id').style.display='';
            document.getElementById('show_id').style.display='none';"
   class="link">
   [ShowBlock1]
</a>
<span id="spoiler_id" style="display: none">
  <a onclick="document.getElementById('spoiler_id').style.display='none';
              document.getElementById('show_id').style.display='';"
     class="link">
  [Hide]
  </a>
<br>
INSERT CONTENT HERE
</span>

<!--Block 2-->
<a id="show_id" 
   onclick="document.getElementById('spoiler_id').style.display='';
            document.getElementById('show_id').style.display='none';"
   class="link">
   [ShowBlock2]
</a>
<span id="spoiler_id" style="display: none">
  <a onclick="document.getElementById('spoiler_id').style.display='none';
              document.getElementById('show_id').style.display='';"
     class="link">
  [Hide]
  </a>
<br>
INSERT CONTENT HERE
</span>

你应该编辑 block 2 的 ID 以确保它指的是它自己而不是其他 block 。只需将 show_idspoiler_id 更改为其他内容,并相应地更改 getElementById()Here's the JSFiddle for that.

关于HTML [Show] 代码 添加 2 个时只显示其中 1 个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41886054/

相关文章:

javascript - AngularJS 在 javascript 而不是 html 中应用过滤器

html - 仅当菜单展开时才需要将菜单下方的内容下推(CSS)

javascript - 为什么内联 JavaScript 在 Internet Explorer 9 中不起作用?

jQuery 隐藏和显示第 n 个元素后的 div 列表

html - CSS 超过 1 个背景,在一个按钮中有渐变

javascript - 在特定轴上旋转对象并停止

html - stackoverflow 网站如何调整其 css 以响应

jquery - 我无法隐藏通过 DOM 操作创建的 div

javascript - .选中复选框时加载内容,未选中时删除内容

javascript - 点击 jquery 显示隐藏的 li