如何在javascript中显示选定的元素

我想打开一个模式,根据所选文本显示pdf,但只显示列表中的第一个。我该怎么办?


索引.html


<p><a id="other-activies-link">Semana Omnistack 11</a></p>

<p><a id="other-activies-link">28ª Semana do IME</a></p>


<div id="myModal" class="modal">

 <div class="modal-content">

  <span class="close">&times;</span>

  <iframe id="myFrame" frameborder="0" allowfullscreen></iframe>

 </div>

</div>

脚本.js


const selectedActivity = document.querySelectorAll("#other-activies-link");


selectedActivity.forEach((link) => {

  link.addEventListener("click", () => {

    document.getElementById(

      "myFrame"

    ).src = `/files/${event.target.textContent}.pdf`;

  });

});



湖上湖
浏览 133回答 3
3回答

慕哥9229398

你不应该使用相同的元素,它可以在这里工作,但它是令人不快的。我用相同的.当然,不会加载。我已经在代码本身中进行了解释。看,如果它对你有用。idclassiframeconst selectedActivity = document.querySelectorAll(".other-activies-link");selectedActivity.forEach((link) => {&nbsp; link.addEventListener("click", (event) => { // pass event parameter here&nbsp;&nbsp;&nbsp; &nbsp; document.getElementById(&nbsp; &nbsp; &nbsp; "myFrame"&nbsp; &nbsp; ).src = `/files/${event.target.innerText}.pdf`; // use innerText instead&nbsp; &nbsp; console.clear();&nbsp; &nbsp; console.log(event.target.innerText);&nbsp; &nbsp; console.log(event.target.textContent);&nbsp; });});<p><a class="other-activies-link">Semana<br> Omnistack 11</a></p><p><a class="other-activies-link">28ª Semana do IME</a></p><div id="myModal" class="modal">&nbsp;<div class="modal-content">&nbsp; <span class="close">&times;</span>&nbsp; <iframe id="myFrame" frameborder="0" allowfullscreen></iframe>&nbsp;</div></div>请参阅和此处之间的区别。innerTexttextContent

HUX布斯

不应使用非唯一 ID。如果将 id 替换为类,则代码应该可以正常工作。

守着星空守着你

您应该改用类,元素的id应始终是唯一的<p><a class="other-activies-link">Semana Omnistack 11</a></p><p><a class="other-activies-link">28ª Semana do IME</a></p><div id="myModal" class="modal">&nbsp;<div class="modal-content">&nbsp; <span class="close">&times;</span>&nbsp; <iframe id="myFrame" frameborder="0" allowfullscreen></iframe>&nbsp;</div></div>这应该有效,const selectedActivity = document.querySelectorAll(".other-activies-link");...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript