将JSON对象数据与各个div连接

时间:2017-03-03 22:47:03

标签: javascript jquery css json

所以我试图建立一个列出各种水果的网站,并指出它们目前是否在季节。我已经构建了一个具有水果名称的JSON对象,这个数组显示了水果在季节中的月份,并且boolean设置为false

我的html每种水果都遵循以下模式:

 <div id="mulberries" class="fruit mulberries">
            <span class="fruitText">Mulberries</span>
            <div class="fruitPic mulberriesPic">
                <div class="layer">
                </div>
            </div>  
        </div>

我的JSON数据

中的每个水果都有一个div

我的JSON数据如下所示:

var fruits = [

        {
            "name":"mulberries",
            "ripeMonths": ["07", "08"],
            "isRipe": false, 
        },
        {
            "name":"nectarines",
            "ripeMonths": ["05", "06", "07", "08", "09", "10"],
            "isRipe": false,
        },
        {
            "name":"oranges",
            "ripeMonths": ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"],
            "isRipe": false,
        },

我从当月获得数据如下:

 var month = new Date();
 var mm = month.getMonth()+1;

 if(mm<10) {
 mm='0'+mm
 }

 month = mm;

如果JSON等于boolean中的任何值,我会利用true对象的数据将month值更改为ripeMonths使用此 for (i = 0; i < fruits.length; i++) { if (fruits[i].ripeMonths.indexOf(month) > -1) { (fruits[i].isRipe) = true } else { (fruits[i].isRipe) = false } }; 数组:

CSS

所以,我希望能够做的是在div class= "layer"上使用JSON,突出显示当前季节的成果,并最终让所有的div显示实际的成熟月份是在悬停事件。我似乎无法弄清楚如何将div数据本身连接到各自的.data(key, value)

到目前为止,我所阅读的内容指向了jQuery的var DailyGraph = userStores.ToList().GroupBy(x => x.TransactionDate.Value.DayOfWeek).Select(pr => new { Day = pr.Key, Sales = pr.Sum(x => x.QuantitySoldTransaction) }); from day in Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>() from graph in DailyGraph.Where(g => g.Day == day).DefaultIfEmpty() select new { Day = day.ToString(), Sales = graph == null ? 0 : graph.Sales } ,但我无法弄清楚如何使其发挥作用。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

您需要动态创建它们,您可以尝试使用这种格式。我只展示了几个嵌套对象,但你也是一样。

使用jQuery非常相似..当你有父对象时,你可以做.innerHTML而不是使用append。

var fruits = [

    {
        "name": "mulberries",
        "ripeMonths": ["07", "08"],
        "isRipe": false,
    },
    {
        "name": "nectarines",
        "ripeMonths": ["05", "06", "07", "08", "09", "10"],
        "isRipe": false,
    },
    {
        "name": "oranges",
        "ripeMonths": ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"],
        "isRipe": false,
    }
];


var month = new Date();
var mm = month.getMonth() + 1;

if (mm < 10) {
    mm = '0' + mm
}

month = mm;

for (i = 0; i < fruits.length; i++) {
    if (fruits[i].ripeMonths.indexOf(month) > -1) {

        (fruits[i].isRipe) = true
    } else {
        (fruits[i].isRipe) = false
    }
};

function render() {
    for (i = 0; i < fruits.length; i++) {
        var fruit = document.createElement('div');
        fruit.setAttribute('id', fruits[i].name);
        fruit.setAttribute('class', 'fruit');

        var fruitText = document.createElement('span');
        fruitText.setAttribute('class', 'fruitText');

        var fruitTextNode = document.createTextNode(fruits[i].name);
        fruitText.appendChild(fruitTextNode);

        fruit.appendChild(fruitText);
        document.body.appendChild(fruit);
    }
}

render();

答案 1 :(得分:0)

你的循环可以在相应的水果DIV中找到layers DIV,并添加或删除影响CSS的类。

for (i = 0; i < fruits.length; i++) {
    if (fruits[i].ripeMonths.indexOf(month) > -1) {
        (fruits[i].isRipe) = true;
        document.querySelector(".fruit." + fruits[i].name + " .layer").classList.add("inseason");
    } else {
        (fruits[i].isRipe) = false;
        document.querySelector(".fruit." + fruits[i].name + " .layer").classList.remove("inseason");
    }
};

答案 2 :(得分:0)

所以,你需要:

  1. 设置水果的名称。
  2. 设定成熟的月份,然后在悬停中显示。
  3. 仅突出显示实际撕裂的水果。
  4. 除非你因为其他强制原因(即它们是一个组件)需要所有HTML,我认为你只能使用data(key, value)(或prop(key, value),无论如何)。< / p>

    您对data的怀疑只是夸大了:也许如果您改为阅读id,您会更好地理解......

    这两种方法之间的唯一区别是$(document).ready(function() { /* * Your fruits here. If you can change the ripe months and set it to * numbers, would make code shorter and faster. If not, just set the var * "month" as you are doing actually with the zero AND as a string * (".toString()"). */ var fruits = [ {"name": "Apple", "ripeMonths": [3]}, {"name": "Banana", "ripeMonths": [8]} ]; var container = $("#fruits"); var month = (new Date().getMonth() + 1); $.each(fruits, function(i, fruit) { /* * We'll create a span for each fruit, set the hover text for the * ripe info and the highligth class. */ var p = $("<p>"); var title = "The fruit is riped on ".concat( fruit.ripeMonths.join(", ") ); // You can concatenate then all in the same line. p.text(fruit.name); // Now the paragraph will show the fruit's ripe months on hover. p.prop("title", title); // Only if is a ripping month. if (fruit.ripeMonths.indexOf(month) != -1) { p.addClass("highligth"); } // We append the new fruit to the fruits container. container.append(p); }); });设置了data-* HTML属性(您可以使用.highligth:hover { /* Visual */ background-color: khaki; }之类的普通attrs执行相同的工作,但我认为分开是很好的那种类型的数据)。对于这种情况,你甚至不需要它;使用title,您可以实现这种悬停效果。

    既然你知道该怎么做,我们就可以开始工作了:

    <!DOCTYPE html>
    <html>
      <head>
      <!-- You can do all of it without jQuery, only pointing it if you don't need it for anything else and want to simplify vendors -->
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <!-- Optional, just because I like it -->
      <meta charset="UTF-8">
      <title>Fruits status</title>
      </head>
      <body>
        <!-- Just to store in a nicely place separated from all other things. -->
        <div id="fruits"></div>
      </body>
    </html>
    <p>
    title

    如果您需要维护实际的HTML结构,只需像使用<div>一样创建所有元素,将<span>设置为主highligth,将文本设置为内部<div class="layer">,并将课程num_of_iters = 10; K = 200; for iter = 1:num_of_iters parfor j = 1:K R = make_random_R(iter,j,.....); % Do something end end 添加到substream_id = (iter - 1) * K + j;