javascript - 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>
解决方案
如果您要隐藏或显示的跨度始终位于包含链接的段落之前,则可以使用 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>
推荐阅读
- pine-script - 如何从 color.new() 中提取颜色
- outlook - 来自加载项的 Outlook 日历背景同步
- javascript - 在 React Native 中需要带有 babel-plugin-inline-import 的 SVG XML 内容
- python - 在 pyqt5 组合框中显示两个值并传递这些值
- python - 如何从 URL 读取图像(urllib.error.HTTPError:HTTP 错误 403:禁止)
- c# - 访问另一个脚本变量,但不能更改游戏内
- reactjs - 开玩笑测试给出错误“无法读取未定义的属性‘createElement’”
- python - Go/Python 异步桥接
- c - 如何解决 C 程序 int main 错误
- opengl - 在相机后面的位置进行广告牌时的伪影