我无法添加带有 JSON 文件填充的按钮

问题描述 投票:0回答:1
javascript html jquery arrays button
1个回答
0
投票

考虑以下内容:https://jsfiddle.net/Twisty/vax2e167/

HTML

<div>
  <div class="d-flex justify-content-around mt-4">
    <a href="#" id="button-1" class="btn btn-primary">
      <img src="" alt="Icon" id="icon-button-1" /> <span>Button 1</span>
    </a>
    <a href="#" id="button-2" class="btn btn-primary">
      <img src="" alt="Icon" id="icon-button-2" /> <span>Button 2</span>
    </a>
    <a href="#" id="button-3" class="btn btn-primary">
      <img src="" alt="Icon" id="icon-button-3" /> <span>Button 3</span>
    </a>
    <a href="#" id="button-4" class="btn btn-primary">
      <img src="" alt="Icon" id="icon-button-4" /> <span>Button 4</span>
    </a>
  </div>
</div>

JavaScript

var myData =
  '[{"id":"repo1","buttons":[{"link":"exmpl.html","icon":"exmpl.png","text":"btn exmpl1"},{"link":"exmpl.html","icon":"exmpl.png","text":"btn exmpl2"},{"link":"exmpl.html","icon":"exmpl.png","text":"btn exmpl3"},{"link":"exmpl.html","icon":"exmpl.png","text":"btn exmpl4"}]},{"id":"repo2","buttons":[{"link":"exmpl.html","icon":"exmpl.png","text":"btn exmpl1"},{"link":"exmpl.html","icon":"exmpl.png","text":"btn exmpl2"},{"link":"exmpl.html","icon":"exmpl.png","text":"btn exmpl3"},{"link":"exmpl.html","icon":"exmpl.png","text":"btn exmpl4"}]}]'

$(function () {
  //var urlParams = new URLSearchParams(window.location.search);
  //var repoId = urlParams.get("id")
  var repoId = "repo2"
  $.post("/echo/json/", { json: myData }, function (data) {
    var repo = data.find((r) => r.id === repoId)
    if (repo.buttons && Array.isArray(repo.buttons)) {
      repo.buttons.forEach((button, index) => {
        var btn = $("#button-" + (index + 1))
        if (btn.length > 0) {
          btn.attr("href", button.link || "#")
          btn.find("img").attr("src", button.icon || "default-icon.png")
          btn.find("span").text(button.text || `Button ${index + 1}`)
        }
      })
    }
  })
})

在此示例中,必须将

<span>
标签添加到 HTML 中才能使您的脚本正常工作。 JSFiddle 是测试模拟 JSON 的好方法,因为它具有 Echo 功能。

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