gpt4 book ai didi

javascript - 直接链接到具有多个模态的开放模态

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:49 24 4
gpt4 key购买 nike

我在一个页面中有多个模态框,当我点击时这些模态框会打开。

但是他们不生成链接

我希望他们有他们自己的链接,例如:www.mywebsite.com/test#myModal1

我尝试了至少 30 个网上可用的代码,但都没有成功

我的每个模态都使用相同的 Javascript 代码,只有一些细微差别

例如,这是我在第五个模态中使用的代码

// Get the modal
var modal = document.getElementsByClassName('modal');

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");


// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close");

// When the user clicks the button, open the modal
btn[0].onclick = function() {
modal[0].style.display = "block";
}

btn[4].onclick = function() {
modal[4].style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span[0].onclick = function() {
modal[0].style.display = "none";
}

span[4].onclick = function() {
modal[4].style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}

最佳答案

  1. 不使用散列;
  2. 而是哈希使用搜索:www.yourwebsite.com?openmodal=modal1;
  3. 您的代码将是最简单的:
// modal dialog opener
const openModalDialog = (modalId) => {
const modal = document.getElementById(modalId);
modal.style.display = "block";
}

// callback
const openModal = () => {
// parse search part in url "openmodal=modal1"
const search = {}
console.log('openModal#11111')
window.location.search.split('&').forEach((item) => {
const [key, value] = item.split('=')
search[key] = value
})
// so, you can now find modal id from your url if its passed:
const modalId = search.openmodal
// and, if id is passed - do a something to open modal:
if (modalId) {
// your code for open modal here
openModalDialog(modalId)
}
}

// add callback to document onLoad event:
window.addEventListener("DOMContentLoaded", openModal)
window.addEventListener("load", openModal)

就是这样。当您打开 url www.yoursite.com?openmodal=myModal5 - id 为 myModal5 的模式将在页面加载后打开。

关于javascript - 直接链接到具有多个模态的开放模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com