首页 > 解决方案 > Javascript 在页面上显示/隐藏多个实例 - 无法更改 ID

问题描述

我在页面上有一个带有 Show/Hide 元素的 JS,这样我的组织中的最终用户可以在不知道 html/js 的情况下添加新内容(多次采访),因此不能为每个实例更改 ID。如果现有脚本可以与添加的 var 一起使用,以允许每个实例的 id 编号更改 (+1),那将是理想的,但是,也欢迎使用新的解决方案。

function showMoreOrLess(thisObj, bonusContent) {
  var caption = thisObj.innerHTML;
  //alert(caption);
  if (caption == "Read more") {
    document.getElementById(bonusContent).style.display = "inline";
    thisObj.innerHTML = "Read less";
  } else {
    document.getElementById(bonusContent).style.display = "none";
    thisObj.innerHTML = "Read more";
  }
}
<p>lots of intro text here</p>
<span id="1" style="display:none">
        <p>Lorem Ipsum is ...</p>
    </span>
<p><a onclick="showMoreOrLess(this,'1');">Read more</a></p>

标签: javascriptshow-hide

解决方案


如果您要隐藏或显示的跨度始终位于包含链接的段落之前,则可以使用 DOM 导航属性。

function showMoreOrLess(thisObj) {
  var caption = thisObj.innerHTML;
  var otherObj = thisObj.parentElement.previousElementSibling;
  if (caption == "Read more") {
    otherObj.style.display = "inline";
    thisObj.innerHTML = "Read less";
  } else {
    otherObj.style.display = "none";
    thisObj.innerHTML = "Read more";
  }
}
<p>lots of intro text here</p>
<span id style="display:none">
        <p>Lorem Ipsum is ...</p>
    </span>
<p><a onclick="showMoreOrLess(this);">Read more</a></p>

<p>Different intro text here</p>
<span style="display:none">
        <p>Blah Blah Blah ...</p>
    </span>
<p><a onclick="showMoreOrLess(this);">Read more</a></p>


推荐阅读