【问题标题】:Connecting JSON object data with individual divs将 JSON 对象数据与单个 div 连接起来
【发布时间】:2017-03-03 22:47:03
【问题描述】:

所以我正在尝试建立一个网站,列出各种水果并指出它们当前是否处于时令状态。我构建了一个 JSON 对象,其中包含水果的名称、一个显示水果季节月份的数组以及一个设置为 falseboolean

我对每种水果的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;

如果month 等于ripeMonths 数组中的任何值,我将利用JSON 对象的数据将boolean 值更改为true

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

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

};

所以,我想要做的是在div class= "layer" 上使用CSS 来突出显示当前时令的水果,并最终让所有的div 指示实际成熟月份处于悬停状态事件。我似乎无法弄清楚如何将JSON 数据本身连接到其各自的div

到目前为止,我所读到的内容指向我们 jQuery 的 .data(key, value),但我不知道如何使它工作。任何帮助将不胜感激。

【问题讨论】:

  • 您是在问如何通过 AJAX 加载数据?
  • mulberries&lt;div id="mulberries" class="fruit" "mulberries"&gt; 中做什么?那应该是课程的一部分吗?
  • @AndrewMyers 我不这么认为,但我会研究 AJAX 看看这是否对我有帮助。
  • @Barmar 应该是&lt;div id="mulberries" class="fruit mulberries"&gt; 我改了。

标签: javascript jquery css json


【解决方案1】:

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

使用 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();

【讨论】:

    【解决方案2】:

    所以,你需要:

    1. 设置水果的名称。
    2. 设置它们的成熟月份,然后悬停显示。
    3. 仅突出显示实际撕裂的果实。

    除非由于其他强制原因(即它们是一个组件),您需要所有 HTML,否则我认为您只能使用 &lt;span&gt;(或 &lt;p&gt;,等等)来做到这一点。

    您对data(key, value) 的怀疑被夸大了:也许如果您改为阅读prop(key, value),您会更好地理解...

    这两种方法之间的唯一区别是data 设置了一个data-* HTML 属性(您可以对id 等普通属性执行相同的工作,但我认为分离该类型的数据很好)。对于这种情况,您甚至不需要它;使用title 可以实现悬停效果。

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

    $(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);
        });
    });
    .highligth:hover {
        /* Visual */
        background-color: khaki;
    }
    <!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>

    如果您需要维护您的实际 HTML 结构,只需像我对&lt;p&gt; 所做的那样创建所有元素,将title 设置为主要&lt;div&gt;,将文本设置为内部&lt;span&gt;,然后添加班级 highligth&lt;div class="layer"&gt;

    【讨论】:

      【解决方案3】:

      您的循环可以找到相应水果 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");
          }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-27
        • 1970-01-01
        • 1970-01-01
        • 2014-05-02
        • 1970-01-01
        • 2015-01-20
        • 1970-01-01
        相关资源
        最近更新 更多