【问题标题】:Problem pulling json content with variable url使用可变 url 提取 json 内容时出现问题
【发布时间】:2022-07-06 18:51:13
【问题描述】:

希望有人能帮我解决这个问题

我的问题是为什么这段代码完全符合我的需要?

var wfComponent;
fetch("https://nube-components.netlify.app/navbar01.json")
  .then((res) => res.text())
  .then((data) => (wfComponent = data))
  .then(() => console.log(wfComponent));

document.addEventListener("copy", function (e) {
  e.clipboardData.setData("application/json", wfComponent);
  e.preventDefault();
});
document.getElementById("navbar01").onclick = function () {
  document.execCommand("copy");
};

这个不做复制到剪贴板部分?

$(".button.copy-button").on("click", function () {
  let tag = $(this).attr("id");
  console.log(tag);

  var wfComponent;
  fetch("https://nube-components.netlify.app/" + tag + ".json")
    .then((res) => res.text())
    .then((data) => (wfComponent = data))
    .then(() => console.log(wfComponent));

  document.addEventListener("copy", function (e) {
    e.clipboardData.setData("application/json", wfComponent);
    e.preventDefault();
  });
  document.getElementById(tag).onclick = function () {
    document.execCommand("copy");
  };
});

现在您可以看到我需要“自动化”JSON 位置和目标按钮部分,我需要每个按钮定位不同的 URL。所以我现在迷失在这个领域,我设法提取该 id 并将其应用于 URL,但内容没有被复制到剪贴板。

我根本不是 JS 专家,所以请随时指出我可能做错的任何事情或任何完全不同的方法

谢谢

【问题讨论】:

    标签: javascript json clipboard


    【解决方案1】:

    因为您在另一个内部使用了 addEventListener。但无论哪种方式,还有另一种(可能是 hacky)方法来实现这一点。

    $(".copy-button").on("click", function(e) {
      let tag = $(this).attr("id");
      fetch("https://nube-components.netlify.app/" + tag + ".json")
        .then((res) => res.text())
        .then((data) => (wfComponent = data))
        .then(() => {
          let copyFrom = document.createElement("textarea");
          document.body.appendChild(copyFrom);
          copyFrom.textContent = wfComponent;
          copyFrom.select();
          document.execCommand("copy");
          copyFrom.remove();
          console.log('COPIED!');
        });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <button id="navbar01" class="copy-button">copy navbar01</button>
    
    <button id="navbar02" class="copy-button">copy navbar02</button>

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 2022-07-05
      • 2011-08-03
      • 2023-03-21
      相关资源
      最近更新 更多