简体   繁体   English

如何在我的选择中从json获取对象数据?

[英]How do I get object data from my json in my select?

So I have a select element and I am appending the data I am getting back from my API. 所以我有一个select元素,我要追加从API返回的数据。

function getHeadData() {
    $("#itemSelect").empty();

    if (headitemData.length < 1) {
        $.getJSON("http://localhost:9000/api/helmets", function (key, value) {
            console.log("request helmets");
            var item = "";
            headitemData = key;
            var len = key.length;
            for (let i = 0; i < len; i++) {
                item += '<option value="' + key + '">' + key[i].Name + '</option>';
            }
            $('#itemSelect').append(item);
        });
    }
    else {
        clearIndex(headitemData);
    }
}

That right there returns this 那里的权利返回 在此处输入图片说明

Which is just what I want. 这就是我想要的。 But if I want to get other data like.. the Icon Let's say I want to log to the console when I select a item from the Select element, how would I do that? 但是,如果我想获取其他数据,例如.. Icon ,那么当我从Select元素中选择一个项目时,我想登录到控制台,该怎么做?

The end goal is to print out the Icon property of the json object when I change item in the Select. 最终目标是在“选择”中更改项目时打印出json对象的Icon属性。

JsonData example JsonData示例

<ItemModel>
<ACrush>+0</ACrush>
<AMagic>-5</AMagic>
<ARange>-2</ARange>
<ASlash>+0</ASlash>
<AStab>+0</AStab>
<DCrush>+43</DCrush>
<DMagic>-3</DMagic>
<DRange>+48</DRange>
<DSlash>+49</DSlash>
<DStab>+47</DStab>
<Icon>
https://vignette.wikia.nocookie.net/2007scape/images/a/a0/3rd_age_full_helmet.png/revision/latest?cb=20141217224936
</Icon>
<MagicDamage>+0%</MagicDamage>
<MeleeStrength>+0</MeleeStrength>
<Name>3rd age full helmet</Name>
<Prayer>+0</Prayer>
<RangedStrength>+0</RangedStrength>
<Slayer>0</Slayer>
<Undead>0</Undead>
</ItemModel>

You can set a data for your option like: 您可以为您的option设置数据,例如:

'<option data-icon="'+ key[i].Icon +'"></option>'

And then you can bind a change for your select after create your list: 然后,您可以在创建列表后绑定更改以供选择:

$('select').on('change', function () {
  const _this = $(this).find(':selected');
  const icon = _this.attr('data-icon');

  console.log(icon);
})

Since you want to use the data in other areas of your code, use a closure to create an environment where your variables don't leak out into the global space. 由于要在代码的其他区域中使用数据,因此请使用闭包创建一个环境,在该环境中变量不会泄漏到全局空间中。 For example, with the callback: 例如,使用回调:

(function () {
  var myData;
  function test(callback) {
   $.getJSON("http://localhost:9000/api/helmets",function  (data) {
        callback(data);
      });
    }
    test(function (data) {
      myData = data;
    });
    function getHeadData() {
      $("#itemSelect").empty();
     if (headitemData.length < 1){
        console.log("request helmets");
        var item = "";
        headitemData = myData;
        var len = myData.length;
        for (let i = 0; i < len; i++) {
            item += '<option value="' +myData+ '">' + myData[i].Name + '</option>';
        }
        $('#itemSelect').append(item);
     }
    else {
      clearIndex(headitemData);
    }
  }
  $("#itemSelect").on("change",function(){
      var value = $(this).val();
      var newData = myData.filter(item=>{
      if(myData.Name==value){
         return item;
      }
    });
   console.log(newData.Icon);
});

myData is cached as a global variable specific to that closure. myData作为该闭包特定的全局变量进行缓存。 Note the other functions will only be able to use that variable once the callback has completed. 请注意,其他函数仅在回调完成后才能使用该变量。

Modified version below: 修改后的版本如下:

    function getHeadData() {
    $("#itemSelect").empty();

    if (headitemData.length < 1) {
        $.getJSON("http://localhost:9000/api/helmets", function (key, value) {
            console.log("request helmets");
            var item = "";
            headitemData = key;
            var len = key.length;
            for (let i = 0; i < len; i++) {
                var icon=key[i].Icon;
                item += '<option data-icon="'+icon+'" value="' + key + '">' + key[i].Name + '</option>';
            }
            $('#itemSelect').append(item);
        });
    }
    else {
        clearIndex(headitemData);
    }
}

Simple test to get the Icon from the first option in select: 从select中的第一个选项获取图标的简单测试:

//Get first option to test output
var test=$("#itemselect option:first");
//Read data-icon
console.log(test.data('icon'));
//To update data-icon
test.data('icon','new icon');

To echo when select is changed 选择更改时回显

$("#itemselect").change(function(e) {
  var optionSelected = $("option:selected", this);
  console.log (optionSelected.data('icon'));

});

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

相关问题 如何让我的数据从我的 IpcMain 返回 - How do I get my Data to return from my IpcMain 如何从我的Json对象获取所有ID,名称值和位置到数组中 - How do I get All ID, Name values and location into array from my Json Object 我得到一个JSON / Javascript对象是因为可以在控制台中看到它,但是如何获取它进行序列化并使数据绑定到Ui元素呢? - I am getting a JSON/Javascript object because I can see it in my console, but how do I get it to serialize and make my data bind to my Ui elements? 如何修改JSON对象? - How do I modify my JSON object? 如何从我的选择选项中获取要输入的数据 - How can I get data to input from my select option 如何将来自asmx的返回数据放入JSON? - How do I put my return data from an asmx into JSON? 如何从HTTP上下文对象获取Post数据 - How do I get Post data from my HTTP context object 如何将 POST 请求中的数据保存为变量,以在 GET 请求中使用? - How do I save my data from my POST request, as a variable, to use in my GET request? 如何创建一个方法来映射我的 JSON 对象以在 vue.js 中设置数据对象的属性? - How do I create a methods that map my JSON object to set properties of data object in vue.js? 如何从我的node.js VM实例在浏览器中查看JSON数据? - How do I view my JSON data in a browser from my node.js VM Instance?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM