简体   繁体   English

难以将对象作为innerHTML添加到javascript / jquery中动态创建的div中

[英]Difficulty adding object as innerHTML to a dynamically created div in javascript/jquery

I have below code in my project 我的项目中有以下代码

HTML: HTML:

<input type="text" id="Num">
<input type="button" value="Insert Div" onClick="insertDiv(getElementById('Num').value)" />
<div class="container">
<div id="main">All starts from here</div>
</div>

Javascript: Javascript:

lookupdata=[
{"id":2,"st":[{"label":"Audi","value":10},{"label":"BMW","value":70}]},
{"id":16,"st":[{"label":"Benz","value":40},{"label":"BMW","value":20}]},
{"id":8,"st":[{"label":"AUDI","value":60},{"label":"Tesla","value":70}]},
{"id":5,"st":[{"label":"MZ","value":30},{"label":"Honda","value":40}]}
];

function insertDiv(Num){
    var ar1=Num.replace('[', '');
    ar1=ar1.replace('[', '');
    ar1=ar1.replace(']', '');
    ar1=ar1.replace(']', '');
    alert(ar1);
    var array = JSON.parse("[" + ar1 + "]");
    alert(JSON.stringify(lookupdata,null,2));
    var i=0;
        for(i;i<array.length;i++)
        {
            $( "<div id='sp"+array[i]+"'>This is div with id "+array[i]+"<div class='st'></div></div>" ).insertAfter( "#main");
        }
}    

Using above code, I can create div dynamically for the input string array - Example: If I input [[8,2,5]], it creates three div with id's - 8,2,5 使用上面的代码,我可以为输入字符串数组动态创建div-示例:如果我输入[[8,2,5]],它将创建ID为-8​​,2,5的三个div

However, I would like to insert st value from the object named 'lookupdata' into the respective id div. 但是,我想将名为“ lookupdata”的对象的st值插入相应的id div中。

The purpose of this is, I want to use st as input to a chart within the inner div (with class 'st'). 这样做的目的是,我想将st用作内部div(带有类“ st”)中图表的输入。

How can I do that? 我怎样才能做到这一点?

Here is the working demo - http://jsfiddle.net/sathish_panduga/3581rh71/7/ 这是工作示例-http: //jsfiddle.net/sathish_panduga/3581rh71/7/

You can use jQuery's grep function which is intended for searching an array. 您可以使用jQuery的grep函数,该函数旨在搜索数组。

function getObjContents(i){
  var arr = $.grep(input, function(e){ 
    return e.id == i; 
  });
  var str="";
  for (var i = 0; i < arr[0].st.length; i++) {
    str += JSON.stringify(arr[0].st[i]);
  }
  return str;
}

You would call it like this: 您可以这样称呼它:

$( "<div id='sp"+array[i]+"'>This is div with id "+array[i]+getObjContents(Num)+"<div class='st'></div></div>" ).insertAfter( "#main");

Demo 演示版

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM