我正在尝试添加几个阅读更多链接。正如您所看到的,提供相同的 ID
是被禁止的并且不起作用。你能用不同的方式帮助实现下面的结果吗?我想在网站上的几个 block 文本上使用此功能...
document.getElementById("read_more").addEventListener( 'click' , changeClass);
function changeClass() {
var content = document.getElementById("extra_content");
var btn = document.getElementById("read_more");
content.classList.toggle('show');
if (content.classList.contains("show")) {
btn.innerHTML = "Show Less";
} else {
btn.innerHTML = "Show More";
}
}
@media (max-width: 650px) {
.extra_content {
display: none;
}
#read_more {
display: block;
}
}
.read_more {
display: none;
}
.show {
display: block!important;
}
<div>
<p>here is some content.</p>
<p id="extra_content" class="extra_content">here is some extra content</p>
<button id="read_more" class="read_more">Show More</button>
<p>here is some content.</p>
<p id="extra_content" class="extra_content">here is some extra content</p>
<button id="read_more" class="read_more">Show More</button>
</div>
谢谢你的时间。
最佳答案
首先让我们解释一下为什么不能对不同的元素使用相同的标识符。所以请阅读下面的documentation状态:
The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).
因此,一种可能的解决方案是通过name
或class
属性查找元素。并基于这些切换类。查找以下示例:
const buttons = document.getElementsByClassName('read_more');
const onButtonClick = (event) => {
const button = event.target;
const dataTarget = button.getAttribute('data-target');
const extraContent = document.getElementById(dataTarget);
button.innerHTML = button.innerHTML === 'Show Less' ? 'Show More' : 'Show Less';
extraContent.classList.toggle('show');
}
const attachingEvent = e => e.addEventListener('click', onButtonClick);
Array.prototype.forEach.call(buttons, attachingEvent);
.extra_content {
display: none;
}
.show {
display: block !important;
}
<div>
<p>here is some content.</p>
<p id="firstTarget" class="extra_content">here is some extra content</p>
<button class="read_more" data-target="firstTarget">Show More</button>
<p>here is some content.</p>
<p id="secondTarget" class="extra_content">here is some extra content</p>
<button class="read_more" data-target="secondTarget">Show More</button>
</div>
希望对您有所帮助!
关于javascript - 使用 JavaScript 的多读或多或少链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59163027/