难以将对象作为innerHTML添加到javascript / jquery中动态创建的div [英] Difficulty adding object as innerHTML to a dynamically created div in javascript/jquery

查看:205
本文介绍了难以将对象作为innerHTML添加到javascript / jquery中动态创建的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有以下代码

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:

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");
        }
}    

使用上面的代码,我可以动态创建div输入字符串数组 -
示例:如果我输入[[8,2,5]],它会创建三个id为id的div - 8,2,5

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

但是,我想将名为'lookupdata'的对象中的st值插入到相应的id div中。

However, I would like to insert st value from the object named 'lookupdata' into the respective id div.

这样做的目的是,我想用st作为输入到内部div中的图表(类'st')。

The purpose of this is, I want to use st as input to a chart within the inner div (with class 'st').

我该怎么做?

这是工作演示 - http://jsfiddle.net/sathish_panduga/3581rh71/7/

Here is the working demo - http://jsfiddle.net/sathish_panduga/3581rh71/7/

推荐答案

你可以使用jQuery的 grep 函数,用于搜索数组。

You can use jQuery's grep function which is intended for searching an array.

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;
}

您可以这样称呼:

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

演示

这篇关于难以将对象作为innerHTML添加到javascript / jquery中动态创建的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆