向Javascript Iframe弹出窗口添加多个链接



我如何向这个JavaScript添加多个链接,JavaScript是一个Iframe弹出窗口,由外部链接触发,我需要添加3个链接来触发3个不同的页面弹出窗口。

我研究过JavaScript并尝试过不同的方法。我搜索了stack,没有找到任何可以提供解决方案的东西。

如有任何帮助,我们将不胜感激。

以下是使用带有1个链接的JavaScript的HTML。

document.getElementById("link").onclick = function(e) {
e.preventDefault();
document.getElementById("popupdarkbg").style.display = "block";
document.getElementById("popup").style.display = "block";
document.getElementById('popupiframe').src = "http://example.com";
document.getElementById('popupdarkbg').onclick = function() {
document.getElementById("popup").style.display = "none";
document.getElementById("popupdarkbg").style.display = "none";
};
return false;
}
window.onkeydown = function(e) {
if (e.keyCode == 27) {
document.getElementById("popup").style.display = "none";
document.getElementById("popupdarkbg").style.display = "none";
e.preventDefault();
return;
}
}
#popup { display: none; position: fixed; top: 12%; left: 15%; width: 70%; height: 70%; background-color: transparent; z-index: 10; }
#popup iframe { width: 100%; height: 100%; border: 0; }
#popupdarkbg { position: fixed; z-index: 5; left: 0; top: 0; width: 100%; height: 100%; overflow: hidden; background-color: rgba(0,0,0,.75); display: none; }
<div id="main">
<a href="" id="link">Click me</a><br>
</div>
<div id="popup"><iframe id="popupiframe"></iframe></div>
<div id="popupdarkbg"></div>

您可以使用class引用多个元素。选择具有querySelectorAll()类的所有元素,然后循环遍历它们以附加事件。

您可以使用自定义属性将元素本身中的相关链接关联起来,然后单击即可检索该链接,并将其设置为弹出的iframesrc

尝试以下方式:

document.querySelectorAll('.link').forEach(function(lk){
lk.onclick = function(e) {
e.preventDefault();
document.getElementById("popupdarkbg").style.display = "block";
document.getElementById("popup").style.display = "block";
document.getElementById('popupiframe').src = this.getAttribute('data-link');
console.log(this.getAttribute('data-link'));
document.getElementById('popupdarkbg').onclick = function() {
document.getElementById("popup").style.display = "none";
document.getElementById("popupdarkbg").style.display = "none";
};
return false;
}
});
window.onkeydown = function(e) {
if (e.keyCode == 27) {
document.getElementById("popup").style.display = "none";
document.getElementById("popupdarkbg").style.display = "none";
e.preventDefault();
return;
}
}
#popup { display: none; position: fixed; top: 12%; left: 15%; width: 70%; height: 70%; background-color: transparent; z-index: 10; }
#popup iframe { width: 100%; height: 100%; border: 0; }
#popupdarkbg { position: fixed; z-index: 5; left: 0; top: 0; width: 100%; height: 100%; overflow: hidden; background-color: rgba(0,0,0,.75); display: none; }
<div>
<a href="" class="link" data-link="http://example.com">Click me</a><br>
<a href="" class="link" data-link="http://example-2.com">Click me 2</a>
</div>
<div id="popup"><iframe id="popupiframe"></iframe></div>
<div id="popupdarkbg"></div>

最新更新