简体   繁体   English

JavaScript-显示弹出窗口

[英]JavaScript - Displaying Popups

I am trying to display different popups based on randomly generated ids. 我试图根据随机生成的ID显示不同的弹出窗口。 The code I am using is as follows (this is done using Toolset Types in WordPress): 我正在使用的代码如下(这是使用WordPress中的“工具集类型”完成的):

    <div class="id-select" id="[random_number]">
    <div class="service-container">
        <div class="service-image">
            [types field="picture"][/types]
        </div>
        <div class="service-text">
            <p><strong>Item:</strong> [wpv-post-title output="sanitize"]</p>
            <p><strong>Suitable For:</strong> [wpv-post-taxonomy type="memorial-category" format="name"]</p>
            <p><strong>Price:</strong> [types field="price"][/types]</p>
        </div>
    </div>
</div>
<!-- The Modal -->
<div id="myModal-custom" class="modal-custom">

    <!-- Modal content -->
    <div class="modal-content-custom">
        <span class="close-custom">×</span>
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6">
                  <div class="service-image">
                    [types field="picture"][/types]
                  </div>
                </div>
                <div class="col-md-6">
                    <div class="service-text">
                        <p><strong>Item:</strong> [wpv-post-title output="sanitize"]</p>
                        <p><strong>Suitable For:</strong> [wpv-post-taxonomy type="memorial-category" format="name"]</p>
                        <p><strong>Price:</strong> [types field="price"][/types]</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

The JavaScript is as follows: JavaScript如下:

// Get the modal
var modal = document.getElementById('myModal-custom');
// Get the button that opens the modal
      var ids = [];
      $('.id-select').each(function(i, el) {
        if (el.id == '') {
          return;
        }
        ids.push('#' + el.id);
      });
      //console.log(ids.join(','));

      $(ids.join(',')).on('click', function(e) {
        modal.style.display = "block";
      })
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close-custom")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.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";
  }
}

The problem im having is that any item i click on the front-end displays the same modal box. 我遇到的问题是,我在前端单击的任何项目都显示相同的模式框。 Is there anyway I can get it to pick up the correct modal box for a specific item? 无论如何,我可以拿起它为特定项目选择正确的模式框吗?

The live site - http://79.170.40.172/tc-pinkfin.co.uk/memorials/cemetery/ 实时网站-http://79.170.40.172/tc-pinkfin.co.uk/memorials/cemetery/

How would you expect modal to be different, when you dont parametrize it in getter anyhow? 当您不以任何方式在getter中对其参数化时,您如何期望模态有所不同?

var modal = document.getElementById('myModal-custom');

You always ask for same modal, so it s always the same. 您总是要求相同的模态,因此它总是相同的。

Do you have more modals on your page? 您的页面上还有更多模式吗?

Do you somehow pass different data to that one modal and it s not displaying? 您是否以某种方式将不同的数据传递给该模式,而该模式却没有显示?

On your page I see you display boxes with images and some additional data. 在您的页面上,我看到您显示带有图像和一些其他数据的框。 Guess you have those images + data in some array like: 猜猜你有那些图像+数据在一些数组中,如:

const items = [
   { imgSrc: "...", additionalData:{...} },
   { imgSrc: "...", additionalData:{...} },
   { imgSrc: "...", additionalData:{...} },
];

Generally what you need do to is to associate modal with each item (from above array) 通常,您需要做的是将模式与每个item相关联(来自上面的数组)

Best moment to do that would be at the time when you create those boxes you already have on your page and want to click to show modal (you do that in a loop, right?). 最好的时机是在创建页面上已有的框并单击以显示模式框时(您可以循环执行,对吗?)。

Possible solutions: 可能的解决方案:

  • when creating each box, you can attach click handler to it, pointing to particular modal instance. 创建每个框时,可以将click handler附加到该click handler ,指向特定的模式实例。
  • extend each item object with unique ID and somehow add that ID to proper modal DOM element for each item. 使用唯一的ID扩展每个item对象,并以某种方式将该ID添加到每个项目的适当模式DOM元素中。 Ex. 防爆。 data-modaluid="$uniqueIDFromItem" Than on click on each item, bind click method with that ID (which can also be set as data-itemuid=$uniqueIDFromItem or just binded in click handler) and by that ID search for proper modal DOM node. data-modaluid="$uniqueIDFromItem"然后单击每个项目,将具有该ID的click方法绑定(也可以将其设置为data-itemuid=$uniqueIDFromItem或仅在单击处理程序中进行绑定),并通过该ID搜索适当的模式DOM节点。

There are few ways to do that depending on how you structurized your page and how you handle your data. 有几种方法可以执行此操作,具体取决于您如何组织页面和如何处理数据。

HTML HTML

<button>toggle modal 1</button>
<button>toggle modal 2</button>
<button>toggle modal 3</button>

<div class="modal">
  modal 1
</div>
<div class="modal">
  modal 2
</div>
<div class="modal">
  modal 3
</div>

Javascript 使用Javascript

General idea is to connect each clickable item with model by unique id (uid). 总体思路是通过唯一的ID(uid)将每个可点击项与模型相关联。

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

document.addEventListener("DOMContentLoaded", () => {
  const modals = document.querySelectorAll(".modal")
  const buttons = document.querySelectorAll("button")

  let guids = []

  //create unique IDs for modals/buttons
  buttons.forEach(button => {
    guids.push(guid())
  })

  //set those IDs for buttons/modals with same order in array. Creating connections  1->1 2->2 3->3
  guids.forEach((guid, index) => {
    buttons[index].dataset.guid = guid
    modals[index].dataset.guid = guid
  })

  //add onClick event listener for each button
  buttons.forEach(button => {
    button.addEventListener("click", (e) => {
       //find proper div modal with same ID as clicked button
       const divModal = document.querySelector(`div[data-guid="${e.target.dataset.guid}"]`)
       //change its style when not visible assign "visible", otherwise assign "hidden"
       divModal.style.visibility = divModal.style.visibility !== "visible" ? "visible" : "hidden";
    })
  })
})

Codepen: Codepen:

https://codepen.io/anon/pen/GXzOJv?editors=1011 https://codepen.io/anon/pen/GXzOJv?editors=1011

Credits 积分

GUID method from here: Create GUID / UUID in JavaScript? 从这里的GUID方法: 在JavaScript中创建GUID / UUID?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM