【问题标题】:Populate jQuery function variables with JSON array data使用 JSON 数组数据填充 jQuery 函数变量
【发布时间】:2021-08-23 19:30:11
【问题描述】:

更新以显示工作脚本。希望这可以帮助某人。 :)

//Parse JSON array into javascript array  - REQUIRED FOR dynamic add
 const tooltime = JSON.parse(toolitems);
  console.log(tooltime);  
  
  //Log items on stop
  const draggableOptions = {
   stop: function(evt, ui){
      logItems()
   }
}
  //end log

     //DYNAMICALLY generate new copies of items
  $("#menu .menu-item").click(function () {
    // find associated item in toolitems.items array
    const tool = tooltime.items.find((o) => o.id === this.id)
    const $div = $("<div>")
    .data('type', this.id)
    .draggable(draggableOptions)
      .css({
        id: "draggable",
        padding: "0.5em",
        float: "left",
        margin: "0 10px 10px 0",
        cursor: "move",
        position: "absolute",
        background: "rgba(245, 245, 245, 0.5)",
        border: "1px solid #ccc"
      })
      .addClass("draggable", "ui-widget-content")
      .append(
        '<div id="block_container"><div class="remove_block"></div><img src="https://assets.codepen.io/759025/' +
          tool.imagefile +
          '" alt="' +
          tool.item +
          '"></div>'
      )
      .css({
        width: 100
      })
      .append('<div>' +
          tool.item +
          '</div>')
    .css({
      "text-align": "center",
      "font-size": "24px",
      padding: " 0.25em",
      "line-height": "100%"
      //"white-space": "nowrap"
    })
      .appendTo("#containment-wrapper")
      .draggable({
        containment: "#containment-wrapper",
        stack: ".draggable",
        scroll: false
      })
      .resizable({
        minHeight: 100,
        minWidth: tool.imagewidth,
        maxHeight: 500,
        maxWidth: 500,
        aspectRatio: false
      })
  });

我有一个 jQuery 函数,可以在单击菜单时动态生成可拖动项目。目前 - 在构建我的应用程序时,我已经为每种类型的可拖动项目编写了一个相同的函数 - 一切正常。我希望将这些组合成一个函数,并从 JSON 数组中填充项目属性。非常感谢任何帮助 - 谢谢!

数组:

var toolitems =
  '{ "items" : [' +
  '{ "id":"firewall" ,"item":"Firewall" , "category":"Network Devices" , "imagefile":"firewall1.svg", "imagewidth":"100" },' +
  '{ "id":"datadiode" ,"item":"Data diode" , "category":"Network Devices" , "imagefile":"datadiode.svg", "imagewidth":"100" },' +
  '{ "id":"router" ,"item":"Router" , "category":"Network Devices" , "imagefile":"router.svg", "imagewidth":"200" },' +
  '{ "id":"switch" ,"item":"Switch" , "category":"Network Devices" , "imagefile":"server.svg", "imagewidth":"200" },' +
    '{ "id":"Server" ,"item":"Server" , "category":"Servers" , "imagefile":"Server", "imagewidth":"200" },' +
  
  '{ "id":"networkL0" ,"item":"L0" , "category":"Network Levels" , "imagefile":"L0.svg", "imagewidth":"200" },' +
  '{ "id":"thecloud" ,"item":"The Cloud" , "category":"Other" , "imagefile":"thecloud.svg", "imagewidth":"100" ]}';

注释我需要添加变量的地方:

功能:

$(function () {

//VARIABLE "id" is example #firewall

  $("#firewall").click(function () {
    var dynamic_div = $(document.createElement("div"))
      .css({
        id: "draggable",
        padding: "0.5em",
        float: "left",
        margin: "0 10px 10px 0",
        cursor: "move",
        position: "absolute",
        background: "rgba(245, 245, 245, 0.5)",
        border: "1px solid #ccc"
      })
      .addClass("draggable", "ui-widget-content");

    $(dynamic_div)
      .append(

//VARIABLE "imagefile" is img srg, VARIABLE "item" is alt

        '<div id="block_container"><div class="remove_block"></div><img src="firewall1.svg" alt="Firewall"></div>'
      )
      .css({
        width: 100
      });

//VARIABLE "item" is example "Firewall"

    $(dynamic_div).append("Firewall").css({
      "text-align": "center",
      "font-size": "24px",
      padding: " 0.25em",
      "line-height": "100%"
    });


    $(dynamic_div)
      .appendTo("#containment-wrapper")
      .draggable({
        containment: "#containment-wrapper",
        stack: ".draggable",
        scroll: false
      })

//VARIABLE "imagewidth" is minWidth

      .resizable({
        minHeight: 100,
        minWidth: 100,
        maxHeight: 500,
        maxWidth: 500,
        aspectRatio: false
      });
  });

//END  
});

【问题讨论】:

    标签: jquery arrays json


    【解决方案1】:

    我昨天在这个 UI 上帮助了你,这是我建议的扩展。

    首先将菜单项的 id 与 toolitems 中的 id 匹配,然后您可以使用 Array#find() 获取创建新元素所需的对象。我对此进行了简化,只得到了一些文本。

    我还使用了一个全局draggableOptions 对象,您可以将其传递给新的元素可拖动方法。 stop 事件使用我昨天提供的关于如何循环所有项目以创建对象数组的建议。

    下面的样式不是很好,项目非常原始,但拖动的工作原理与您可以存储的项目元数据数组的日志记录一样

    const draggableOptions = {
       stop: function(evt, ui){
          logItems()
       }
    }
    
    $('#menu .product-add').click(function(){
       // find associated item in toolitems.items array
       const tool = toolitems.items.find(o=> o.id===this.id)
       // only getting text for now. You can extend this for image, category etc
       const $div = $('<div>').data('type', this.id)
                              .text(tool.item)
                              .draggable(draggableOptions);
                              
       $('#containment-wrapper').append($div)             
    
    })
    
    function logItems() {
      const dataArr = $('#containment-wrapper').children().map(function () {
          const $el = $(this);
          const obj = {
            type: $el.data('type'), // from data attribute,
            left: $el.css('left'),
            top: $el.css('top'),
            zIndex: $el.css('zIndex'),
          };
          return obj;
        }).get();
      console.log(dataArr);
    }
    #containment-wrapper {
      margin-left: 200px;
      height: 90vh;
      padding: 0.5em;
      background-repeat: no-repeat;
      background-clip: padding-box;
      background-position: 50% 25%;
      background-size:80%;
    }
    
    #outsidecontainer {
      border: 2px solid gray;  
    }
    
    #menucontainer {
      height: 100%;
      float: left;
      position: fixed;
      width: 200px;
      z-index: 1;
    }
    
    .remove_block{
      width: 100%;
      text-align: right;
      margin: 0 0 10px 0;
      cursor: default;
    }
    
    div.remove_block:after{
      display: inline-block;
      content: "\00d7"; /* This will render the 'X' */
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <div id="outsidecontainer">
      <div id="menucontainer">
         <h4>Products</h4>
        <ul id="menu">
         
          <li>
            <div class="product-add" id="router">Router</div>
          </li>
          <li>
            <div class="product-add" id="firewall">Firewall</div>
          </li>
         
        </ul>
       
      </div>
      <div id="containment-wrapper">
      </div>
      </div>
      
      <script>var toolitems =
      { "items" : [
      { "id":"firewall" ,"item":"Firewall" , "category":"Network Devices" , "imagefile":"firewall1.svg", "imagewidth":"100" },
      { "id":"datadiode" ,"item":"Data diode" , "category":"Network Devices" , "imagefile":"datadiode.svg", "imagewidth":"100" },
      { "id":"router" ,"item":"Router" , "category":"Network Devices" , "imagefile":"router.svg", "imagewidth":"200" },
      { "id":"switch" ,"item":"Switch" , "category":"Network Devices" , "imagefile":"server.svg", "imagewidth":"200" },
      { "id":"Server" ,"item":"Server" , "category":"Servers" , "imagefile":"Server", "imagewidth":"200" },  
      { "id":"networkL0" ,"item":"L0" , "category":"Network Levels" , "imagefile":"L0.svg", "imagewidth":"200" },
      { "id":"thecloud" ,"item":"The Cloud" , "category":"Other" , "imagefile":"thecloud.svg", "imagewidth":"100" }]};</script>

    【讨论】:

    • 非常感谢。我想我知道它是如何从数组中提取出来的。
    • 是直接从 JSON 数据中获取信息更直接,还是应该先将其解析为 javascript 数组?
    • 您必须将其解析为 javascript 才能进行迭代并使元素成为对象。请注意,以您所做的方式手动创建 JSON 不是很有用且难以使用
    • 是的,谢谢...我最终将从数据库中检索 JSON 数据,但首先需要所有客户端功能。试图在未来证明它只是一点点。 :)
    • 在我的回答中,如果您将 toolitems = 之后的所有内容粘贴到 json 文件中并从服务器获取它,它将正常解析。或者将其粘贴到 JSON 验证器中,它将通过
    猜你喜欢
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-09
    相关资源
    最近更新 更多