javascript - 在页面上隐藏/显示多次

标签 javascript html css

首先,我知道这个问题已经在这个网站上回答了很多次,这是这里的主要问题。我在答案中被宠坏了,并且已经搜索了几个小时,没有找到任何直接相似的东西。一定有很多方法可以做到这一点,但我现在拥有的最接近我想要的。

目前我的代码有这个,出于某种原因 fiddle 无法工作,虽然它在我的代码中工作正常,但一定是遗漏了什么。

http://jsfiddle.net/PVLMX/

HTML:

<div id="wrap">
    <p>This text is visible, but there is more.<a href="#" id="example-show"               class="showLink" onclick="showHide('example');return false;"><br/><br/>See more >></a>
    </p> 
    <div id="example" class="more">
        <p>Congratulations! You've found the magic hidden text! Clicking the link below
            will hide this content again.</p>
        <p><a href="#" id="example-hide" class="hideLink" 
            onclick="showHide('example');return false;">Hide this content >></a></p>
    </div>
</div>

Javascript:

function showHide(shID) {
       if (document.getElementById(shID)) {
          if (document.getElementById(shID+'-show').style.display != 'none') {
             document.getElementById(shID+'-show').style.display = 'none';
             document.getElementById(shID).style.display = 'block';
          }
          else {
             document.getElementById(shID+'-show').style.display = 'inline';
             document.getElementById(shID).style.display = 'none';
          }
       }
    }

我需要能够为页面上的每个新“阅读更多”调用该函数。目前,第一个“查看更多”始终是 javascript 的目标,我不确定如何为页面上的其他链接调用此函数。

最佳答案

在 HTML 中,每个 id=""必须是一个唯一标识符,你不能放两个 id="example"所以你需要 id="example"和 id="example2"等等。

工作 jsfiddle:http://jsfiddle.net/PVLMX/2/

<div id="wrap">
    <p>This text is visible, but there is more.<a href="#" id="example2-show"  
     class="showLink" onclick="showHide('example2');return false;"><br/><br/>See more >></a>
    </p> 
    <div id="example2" class="more">
        <p>This text was hidden, now you see it</p>
        <p><a href="#" id="example2-hide" class="hideLink" 
            onclick="showHide('example2');return false;">Hide this content >></a></p>
    </div>
</div>

我改变了什么:

  1. 第二个 div 中的每个 id="example.. 到 id="example2...。
  2. 以“No wrap - in head”模式加载脚本(jsfiddle 左侧选项)

关于javascript - 在页面上隐藏/显示多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22495702/

相关文章:

html - 谷歌字体 CSS 自定义

html - 输入文本中的图像

javascript - 在视口(viewport)上检测

css - 变换平移和 e.pageX/e.pageY 坐标不同

javascript - 在 Express/Node.js 中渲染 MySQL 结果 : Cannot assign to read only property '_locals'

jquery - 有没有比这更快的方法一次插入所有图片

javascript - 如何在 JavaScript 中检测滑动?

javascript - 参数数量未知的 Controller ?

javascript - 那里有什么好的客户端股票图表库吗?

javascript - 将node.js代码编译为非node需要的代码