我怎样才能让函数在模态中工作?

问题描述 投票:0回答:1

我正在编写一个工作脚本,在编写代码的过程中,我更改了代码以在模式中提取大部分 HTML。我的问题是,我已经制作了很多现在无法与模式中的内容一起使用的功能。我想尝试通过尽可能少的更改来使我的函数与模态一起工作,但恐怕我将不得不重写所有代码。

这是我的代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Zoho Desk - Apps</title>
    <style>
      .hidden {
        display: none;
      }
      .container {
        display: flex;
        justify-content: left;
        align-items: flex-start;
      }
      .content {
        flex: 1;
      }
      .sidebar {
        flex: 0 0 60px;
        position: fixed;
        right: 20px;
      }
      ul {
        list-style-type: none;
        padding: 0;
      }
      li {
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      li button {
        margin-left: 10px;
      }
      .popup {
        position: fixed;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        padding: 20px;
        background-color: white;
        border: 1px solid black;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
        z-index: 1000;
      }
      .overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 999;
      }
      .img {
        right: 20px;
        bottom: 0;
        position: fixed;
      }
      .grid-container {
        display: grid;
        gap: 10px;
      }
      .grid-container > div {
        display: none; /* Hide all divs initially */
      }
      .grid-container > div:not(.hidden) {
        display: grid;
        gap: 10px;
        width: 100px;
        height: 100px;
      }
      .grid-container > div:not(.hidden) button {
        display: grid;
        gap: 10px;
      }
      .Btn {
        width: 100%;
        height: 100%;
        flex-grow: 1;
        background-color: aliceblue;
        color: black;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 1px;
        border: 2px solid dimgray;
        font-family: "Times New Roman", serif;
        text-align: center;
        margin-bottom: 10px;
      }
      .Btn:hover {
        background-color: lightslategrey;
        color: white;
      }
    </style>
  </head>
  <body>
    <a
      target="_blank"
      href="http://helpdesk.wiki.clacorp.com/index.php/Main_Page"
    >
      <img class="img" src="/app/img/img2.png" alt="Wiki" />
    </a>
    <button id="openModalBtn">Open Modal</button>
    <div id="popup" class="popup hidden">
      <div id="popupContent"></div>
      <button onclick="closePopup2()">Close</button>
    </div>
    <div id="overlay" class="overlay hidden" onclick="closePopup2()"></div>
    <script src="https://js.zohostatic.com/support/developer_sdk/v1/js/ZohoDeskClientSDK.min.js"></script>
    <script>
      function openPopupInNewWindow() {
        const newWindow = window.open(
          "",
          "Popup",
          "width=" + screen.width + ",height=" + screen.height
        );
        if (newWindow) {
          newWindow.document.write(`
                    <style>
                        .hidden {
                            display: none;
                        }
                    </style>
                    <div class="container">
                        <div class="content">
                            <input type="text" id="callerName" placeholder="Caller Name"><br>
                            <input type="text" id="EquipmentName" placeholder="Equipment with issue"><br>
                            <input type="text" id="SymptomName" placeholder="Symptoms of Device"><br>
                            <input type="text" id="IssueName" placeholder="Issue"><br>
                            <select id="dropdown" onchange="showOptionsDiv()">
                                <option value=""></option>
                                <optgroup label="PC">
                                    <option value="Cookies">Cookie Bake</option>
                                    <option value="Monitor issues">Monitor issues</option>
                                    <option value="Taskbar Gone">Taskbar Gone</option>
                                    <option value="EFI Shell">EFI Shell Error</option>
                                    <option value="Proxy">Proxy Issue</option>
                                    <option value="Cache">Cache Issue</option>
                                    <option value="NewPC">New PC Setup</option>
                                </optgroup>
                                <optgroup label="Router/Modem">
                                    <option value="Site Down">Site Down</option>
                                    <option value="ISP">ISP</option>
                                    <option value="4G">4G card</option>
                                    <option value="Crash Pack">Crash Pack</option>
                                </optgroup>
                                <optgroup label="VOIP Phones">
                                    <option value="Forward">Forward Calls</option>
                                    <option value="Phone Issues">Connection Issues</option>
                                </optgroup>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="sidebar">
                            <ul id="optionsList"></ul>
                            <button onclick="generateBulletedList()">Generate Bulleted List</button>
                            <button onclick="window.close()">Close</button>      
                        </div>
                    </div>
                `);
          popup.classList.remove("hidden");
          overlay.classList.remove("hidden");
        } else {
          console.error("Popup elements not found.");
        }
      }
      function closePopup() {
        window.close();
      }
      // Add your existing JavaScript functions here (showOptionsDiv, addItemToList, etc.)
    </script>
    <script>
      document
        .getElementById("openModalBtn")
        .addEventListener("click", function () {
          openPopupInNewWindow();
        });

      document
        .getElementById("callerName")
        .addEventListener("keypress", function (e) {
          if (e.key === "Enter") {
            const callerName = document
              .getElementById("callerName")
              .value.trim();
            if (callerName !== "") {
              addItemToList(callerName, true, "Caller: ", "callerOptionsList");
              document.getElementById("callerName").value = "";
            }
          }
        });

      document
        .getElementById("EquipmentName")
        .addEventListener("keypress", function (e) {
          if (e.key === "Enter") {
            const EquipmentName = document
              .getElementById("EquipmentName")
              .value.trim();
            if (EquipmentName !== "") {
              addItemToList(
                EquipmentName,
                true,
                "Equipment: ",
                "equipmentOptionsList"
              );
              document.getElementById("EquipmentName").value = "";
            }
          }
        });

      document
        .getElementById("SymptomName")
        .addEventListener("keypress", function (e) {
          if (e.key === "Enter") {
            const SymptomName = document
              .getElementById("SymptomName")
              .value.trim();
            if (SymptomName !== "") {
              addItemToList(
                SymptomName,
                true,
                "Symptoms: ",
                "SymptomOptionsList"
              );
              document.getElementById("SymptomName").value = "";
            }
          }
        });

      document
        .getElementById("IssueName")
        .addEventListener("keypress", function (e) {
          if (e.key === "Enter") {
            const IssueName = document.getElementById("IssueName").value.trim();
            if (IssueName !== "") {
              addItemToList(IssueName, true, "Issue: ", "IssueOptionsList");
              document.getElementById("IssueName").value = "";
            }
          }
        });

      document.addEventListener("DOMContentLoaded", function () {
        setupEventListeners();
      });

      function setupEventListeners() {
        addEnterKeyEventListener("callerName", "Caller: ", "callerOptionsList");
        addEnterKeyEventListener(
          "EquipmentName",
          "Equipment: ",
          "equipmentOptionsList"
        );
        addEnterKeyEventListener(
          "SymptomName",
          "Symptoms: ",
          "SymptomOptionsList"
        );
        addEnterKeyEventListener("IssueName", "Issue: ", "IssueOptionsList");
        document
          .getElementById("dropdown")
          .addEventListener("change", showOptionsDiv);
      }

      function addEnterKeyEventListener(inputId, staticText, listId) {
        const inputElement = document.getElementById(inputId);
        if (inputElement) {
          inputElement.addEventListener("keypress", function (e) {
            if (e.key === "Enter") {
              const inputValue = inputElement.value.trim();
              if (inputValue !== "") {
                addItemToList(inputValue, true, staticText, listId);
                inputElement.value = "";
              }
            }
          });
        } else {
          console.error(`Element with ID '${inputId}' not found.`);
        }
      }

      function showOptionsDiv() {
        const selectedOption = document.getElementById("dropdown").value;
        const optionsDiv = document.getElementById("optionsDiv");
        if (!optionsDiv) {
          console.error("Element with ID 'optionsDiv' not found.");
          return;
        }
        const divs = optionsDiv.querySelectorAll("div");
        divs.forEach(function (div) {
          div.classList.add("hidden");
        });
        if (selectedOption) {
          const divToShow = document.getElementById(selectedOption + "Div");
          if (divToShow) {
            optionsDiv.classList.remove("hidden");
            divToShow.classList.remove("hidden");
          } else {
            console.error(`Element with ID '${selectedOption}Div' not found.`);
          }
        } else {
          optionsDiv.classList.add("hidden");
        }
      }

      function addOptionToList(selectId, optionId) {
        const select = document.getElementById(selectId);
        if (!select) {
          console.error(`Element with ID '${selectId}' not found.`);
          return;
        }
        const selectedOption = select.options[select.selectedIndex];
        const optionText = selectedOption.text;
        const optionValue = selectedOption.value;
        const listItem = document.createElement("li");
        listItem.textContent = optionText;
        listItem.setAttribute("value", optionValue);
        listItem.setAttribute("id", optionId);
        addButtonsToListItem(listItem, optionText);
        const optionsList = document.getElementById("optionsList");
        if (optionsList) {
          optionsList.appendChild(listItem);
        } else {
          console.error("Element with ID 'optionsList' not found.");
        }
      }

      let firstItemAdded = false;

      function addCustomOptionToList() {
        const staticText = "- ";
        const customOption = prompt("Enter custom option:");
        if (customOption !== null && customOption !== "") {
          const listItem = document.createElement("li");
          listItem.textContent = staticText + customOption;
          addButtonsToListItem(listItem, customOption);
          const optionsList = document.getElementById("optionsList");
          if (optionsList) {
            if (!firstItemAdded) {
              const troubleshootingSteps = document.createElement("li");
              troubleshootingSteps.textContent = "Troubleshooting Steps:";
              optionsList.appendChild(troubleshootingSteps);
              firstItemAdded = true;
            }
            optionsList.appendChild(listItem);
          } else {
            console.error("Element with ID 'optionsList' not found.");
          }
        }
      }

      function Transfer() {
        const staticText = "Transferred Calls From ";
        let customOption1 = prompt("From Site:");
        ZOHODESK.set("ticketForm.cf_site_transferring_from", {
          value: customOption1,
        });
        if (customOption1 !== null && customOption1 !== "") {
          let customOption2 = prompt("To site:");
          ZOHODESK.set("ticketForm.cf_site_transferring_to", {
            value: customOption2,
          });
          if (customOption2 !== null && customOption2 !== "") {
            const listItem = document.createElement("li");
            listItem.textContent =
              staticText + customOption1 + " to " + customOption2;
            addButtonsToListItem(
              listItem,
              customOption1 + "  " + customOption2
            );
            const optionsList = document.getElementById("optionsList");
            if (optionsList) {
              optionsList.appendChild(listItem);
            } else {
              console.error("Element with ID 'optionsList' not found.");
            }
          }
        }
      }

      function vnc(option, isTextInput = false, staticText, listId) {
        const staticTextWithCustomOption = "- VNC into PC with IP: 10.30.";
        const staticTextWithoutCustomOption = "- VNC into PC";
        const customOption = prompt(
          "- VNC into PC              No input = No IP"
        );
        if (customOption !== null && customOption !== "") {
          const listItem = document.createElement("li");
          listItem.textContent = staticTextWithCustomOption + customOption;
          addButtonsToListItem(listItem, customOption);
          const optionsList = document.getElementById("optionsList");
          if (optionsList) {
            optionsList.appendChild(listItem);
          } else {
            console.error("Element with ID 'optionsList' not found.");
          }
        } else {
          const listItem = document.createElement("li");
          listItem.textContent = staticTextWithoutCustomOption;
          addButtonsToListItem(listItem, "");
          const optionsList = document.getElementById("optionsList");
          if (optionsList) {
            if (!firstItemAdded && !isTextInput) {
              const troubleshootingSteps = document.createElement("li");
              troubleshootingSteps.textContent = "Troubleshooting Steps:";
              optionsList.appendChild(troubleshootingSteps);
              firstItemAdded = true;
            }
            optionsList.appendChild(listItem);
          } else {
            console.error("Element with ID 'optionsList' not found.");
          }
        }
      }

      function Puttyip(option, isTextInput = false, staticText, listId) {
        const staticTextWithCustomOption = "- Putty into PC with IP: 10.30.";
        const staticTextWithoutCustomOption =
          "- Putty into PC              No input = No IP";
        const customOption = prompt("IP - 10.30. :");
        if (customOption !== null && customOption !== "") {
          const listItem = document.createElement("li");
          listItem.textContent = staticTextWithCustomOption + customOption;
          addButtonsToListItem(listItem, customOption);
          const optionsList = document.getElementById("optionsList");
          if (optionsList) {
            optionsList.appendChild(listItem);
          } else {
            console.error("Element with ID 'optionsList' not found.");
          }
        } else {
          const listItem = document.createElement("li");
          listItem.textContent = staticTextWithoutCustomOption;
          addButtonsToListItem(listItem, "");
          const optionsList = document.getElementById("optionsList");
          if (optionsList) {
            if (!firstItemAdded && !isTextInput) {
              const troubleshootingSteps = document.createElement("li");
              troubleshootingSteps.textContent = "Troubleshooting Steps:";
              optionsList.appendChild(troubleshootingSteps);
              firstItemAdded = true;
            }
            optionsList.appendChild(listItem);
          } else {
            console.error("Element with ID 'optionsList' not found.");
          }
        }
      }

      function addItemToList(option, isTextInput = false, staticText, listId) {
        const listItem = document.createElement("li");
        if (isTextInput) {
          listItem.textContent = staticText + option;
        } else {
          listItem.textContent = option;
        }
        addButtonsToListItem(listItem, option);
        const optionsList = document.getElementById("optionsList");
        if (optionsList) {
          if (!firstItemAdded && !isTextInput) {
            // need to add option to remove none from input fields
            const troubleshootingSteps = document.createElement("li");
            troubleshootingSteps.textContent = "Troubleshooting Steps:";
            optionsList.appendChild(troubleshootingSteps);
            firstItemAdded = true;
          }
          optionsList.appendChild(listItem);
        } else {
          console.error("Element with ID 'optionsList' not found.");
        }
      }

      function ispoutage(option, isTextInput = false, staticText, listId) {
        const listItem = document.createElement("li");
        if (isTextInput) {
          listItem.textContent = staticText + option;
        } else {
          listItem.textContent = option;
        }
        addButtonsToListItem(listItem, option);
        const optionsList = document.getElementById("optionsList");
        if (optionsList) {
          if (!firstItemAdded && !isTextInput) {
            const troubleshootingSteps = document.createElement("li");
            troubleshootingSteps.textContent = "Troubleshooting Steps:";
            optionsList.appendChild(troubleshootingSteps);
            firstItemAdded = true;
          }
          optionsList.appendChild(listItem);
        } else {
          console.error("Element with ID 'optionsList' not found.");
        }
        ZOHODESK.set("ticketForm.cf_outtage", { value: true });
      }

      function addButtonsToListItem(listItem, optionText) {
        const removeButton = document.createElement("button");
        removeButton.textContent = "Remove";
        removeButton.onclick = function () {
          listItem.remove();
        };
        listItem.appendChild(removeButton);

        const repeatButton = document.createElement("button");
        repeatButton.textContent = "Repeat";
        repeatButton.onclick = function () {
          repeatOption(optionText);
        };
        listItem.appendChild(repeatButton);

        const noteButton = document.createElement("button");
        noteButton.textContent = "Note";
        noteButton.onclick = function () {
          writeNoteInput(listItem);
        };
        listItem.appendChild(noteButton);
      }

      function writeNoteInput(listItem) {
        if (listItem.querySelector(".note-input")) {
          return;
        }
        const staticText = "";
        const noteInput = document.createElement("input");
        noteInput.type = "text";
        noteInput.placeholder = "Write your note here";
        noteInput.classList.add("note-input");

        const saveButton = document.createElement("button");
        saveButton.textContent = "Save Note";
        saveButton.onclick = function () {
          addNoteToItem(listItem, noteInput.value);
          noteInput.remove();
          saveButton.remove();
        };

        noteInput.addEventListener("keydown", function (event) {
          if (event.key === "Enter") {
            event.preventDefault();
            addNoteToItem(listItem, noteInput.value);
            noteInput.remove();
            saveButton.remove();
          }
        });

        listItem.appendChild(document.createTextNode(staticText));
        listItem.appendChild(noteInput);
        listItem.appendChild(saveButton);
      }

      function addNoteToItem(listItem, note) {
        if (note.trim() !== "") {
          let sublist = listItem.querySelector("ul");
          if (!sublist) {
            sublist = document.createElement("ul");
            listItem.appendChild(sublist);
          }
          const noteListItem = document.createElement("li");
          noteListItem.textContent = note;
          sublist.appendChild(noteListItem);
        }
      }

      function showPopupAndCopy(predefinedText) {
        const popup = document.getElementById("popup");
        const popupText = document.getElementById("popupText");
        if (popup && popupText) {
          popupText.textContent = predefinedText;
          popup.classList.remove("hidden");
          document.getElementById("overlay").classList.remove("hidden");
          navigator.clipboard
            .writeText(predefinedText)
            .then(() => {
              console.log("Text copied to clipboard");
            })
            .catch((err) => {
              console.error("Could not copy text: ", err);
            });
        } else {
          console.error("Popup elements not found.");
        }
      }

      function closePopup2() {
        const popup = document.getElementById("popup");
        if (popup) {
          popup.classList.add("hidden");
        } else {
          console.error("Element with ID 'popup' not found.");
        }
        const overlay = document.getElementById("overlay");
        if (overlay) {
          overlay.classList.add("hidden");
        } else {
          console.error("Element with ID 'overlay' not found.");
        }
      }

      function generateBulletedList() {
        const listItems = document.getElementById("optionsList").children;
        let nonBulletedList = "";
        for (let i = 0; i < listItems.length; i++) {
          const listItemText = listItems[i].childNodes[0].textContent.trim();
          nonBulletedList += listItemText + "\n";
          const sublistItems = listItems[i].querySelectorAll("ul > li");
          for (let j = 0; j < sublistItems.length; j++) {
            nonBulletedList +=
              "  -  " + sublistItems[j].textContent.trim() + "\n";
          }
          if (listItemText.startsWith("Caller:")) {
            nonBulletedList += "\n";
          }
          if (listItemText.startsWith("Equipment:")) {
            nonBulletedList += "\n";
          }
          if (listItemText.startsWith("Symptoms:")) {
            nonBulletedList += "\n";
          }
          if (listItemText.startsWith("Issue:")) {
            nonBulletedList += "\n";
          }
        }
        const textArea = document.createElement("textarea");
        textArea.value = nonBulletedList;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand("copy");
        document.body.removeChild(textArea);
        alert("List copied to clipboard:\n\n" + nonBulletedList);
        ZOHODESK.set("ticketForm.description", { value: nonBulletedList });
      }

      function repeatOption(optionText) {
        const repeatedItem = document.createElement("li");
        repeatedItem.textContent = optionText + " again";
        addButtonsToListItem(repeatedItem, optionText);
        document.getElementById("optionsList").appendChild(repeatedItem);
      }

      ZOHODESK.invoke("RESIZE", { width: "455px", height: "545px" });

      App.instance.on("ticket.update", function (data) {
        //data gives the ticket details
      });

      window.onload = function () {
        ZOHODESK.extension.onload().then(function (App) {
          //Get ticket related data
          ZOHODESK.get("ticket.email")
            .then(function (res) {
              //response Handling
            })
            .catch(function (err) {
              //error Handling
            });
        });
      };

      // notes in description box
      //connect to clawsmachine to pull info and dump in description
    </script>
    <script src="./js/extension.js" charset="utf-8"></script>
  </body>
</html>

我删除了一些 html 代码以使其符合字符限制

我尝试将javascript放在我的模态中,但这破坏了我的所有代码,并且我尝试寻找不同的方法来编写函数,但我似乎找不到任何使模态接受函数的东西

javascript html css bootstrap-modal
1个回答
0
投票

一般来说,您的问题如下:

  • 你有一些 HTML
  • 您已经为该 HTML 编写了一些 Javascript
  • 您将该 HTML 移至引导模式中
  • 您的 Javascript 无法在 Bootstrap 模式中运行

由于您在问题中粘贴了太多代码,并且没有描述所有问题,从我们的角度来看,我们需要使用您的截断代码建立一个测试环境,测试并猜测您的确切期望是什么。由于这样做超出了志愿者问答的范围,因此我将为您提供有关执行此类操作时可能出现的典型问题的指导以及这些问题的典型解决方案。如果您发现我的答案太模糊,那么您需要编辑您的问题,将问题范围缩小到单个问题,并在评论部分通知我。言归正传,以下是将内容移动到这样的模式中的典型问题以及这些典型问题的典型解决方案:

1.环境变化

您的初始上下文是整个 HTML,但将其作为上下文移动到模式中会改变其上下文。因此,使用选择器的样式和 Javascript 代码不再仅适用于您放入模态的内容,也适用于模态之外的元素。

解决方案:确保您有一个已移入模式的 HTML 的父容器,并将所有选择器更改为指定此类父级的存在。

示例:

.container p {
    color: red;
}
<p>abc</p>
<div class="container">
    <p>def</p>
</div>
<p>ghi</p>

请注意,我已指定我的样式适用于

.container
的后代,因此它之外的内容将被忽略。

2.无效的 HTML

如果您没有使用 iframe 并将整个内容粘贴到 iframe 中,包括 doctype、html 标签等,那么您的 HTML 无效。在您的页面上运行 HTML 验证器并修复任何导致 HTML 无效的问题

3.事件未触发

您定义了事件,例如加载事件之类的东西。然而,您的模态内容应该在模态打开时执行加载事件。因此,实现一个函数来执行模式打开时需要执行的操作并在模式打开时调用它是可行的。请参阅在 Bootstrap 模式打开时调用函数

© www.soinside.com 2019 - 2024. All rights reserved.