如何在jQuery中搜索JSON

How to search JSON in jQuery

本文关键字:搜索 JSON jQuery      更新时间:2023-09-26

你好,我有 3 个包含 1,2,3 的 DIV

<div>1</div>
<div>2</div> 
<div>3</div>

并拥有此 JSON

[{
    "FactoreId:1": "FactoreItems:a, b, c, d, e"
}, {
    "FactoreId:2": "FactoreItems:g,f"
}, {
    "FactoreId:3": "FactoreItems:i, k, h"
}]

我希望当我将鼠标悬停在 DIV 上时检查它们的值。

如果 DIV 包含 1 显示 "FactoreId:1": "FactoreItems:a, b, c, d, e" 的因子项,

如果它包含2显示"FactoreId:2": "FactoreItems:g,f"的因子项,依此类推....

您发布的 JSON 不正确,请将其修复为"FactoreId" : num, "FactoreItems": "string"

.HTML

<div>1</div>
<div>2</div>
<div>3</div>

jQuery

 //Fixed JSON
 var factore = [{
       "FactoreId": 1, 
       "FactoreItems": "a, b, c, d, e"
   }, {
       "FactoreId": 2,
       "FactoreItems": "g,f"
   }, {
       "FactoreId": 3,
       "FactoreItems": "i, k, h"
   }]
    $('div').on('mouseover', function () {
        $(this).text("FactoreID : "+factore[$(this).text() -1].FactoreId +"FactoreItems"+ factore[$(this).text()-1].FactoreItems);
   });

演示

解释

因子:是带有 JSON 的数组

$(this).text() -1 返回divs 编号和 -1,因为数组从 0 开始

factore[$(this).text() - 1] 
// if you mouseover div with text one the result will be factore[0]
// then use .FactoreId to get id value