我创建了一个 JSON 文件 mystatsjson.js,其格式如下:
var myJSON = [
{
"ProdID": 204,
"Title": "The best basket in town",
"FB": 32,
"Twit": 45
},
{
"ProdID": 201,
"Title": "The best soap in the whole of US",
"FB": 23,
"Twit": 0
},
{
"ProdID": 103,
"Title": "Limited quantity only",
"FB": 12,
"Twit": 3
},
and so on]
我想编写一个 jQuery 函数,它接收 ID 参数,将其与 myJSON 的 ProdID 进行匹配,并检索该 ID 的 FB 和 Twit 编号。
完成后,它会填充以下内容 <span>
在此 HTML 中包含这些数字。 “FB”的值将填充在 fblink 的范围中,“Twit”的值将显示在 twitlink 的范围中:
<div class="displ">
<a class="button__link" id="fblink" target="_blank" aria-label="">
<div class="button--small"><div class="button__icon">
<svg version="1.1" x="0px" y="0px">
<g>
<path d="M19"/>
</g>
</svg>
<span></span>
</div>
</div>
</a>
<a class="button__link" id="twtlink" target="_blank" aria-label="">
<div class="button--small"><div class="button__icon">
<svg version="1.1" x="0px" y="0px">
<g>
<path d="M23"/>
</g>
</svg>
<span></span>
</div>
</div>
</a>
</div>
我怎样才能实现这个目标。另外,如果 ID 在 myJSON 中不匹配,如何为 FB 和 Twit 提供默认值?
这是我的想法,但不知道。
$(document).ready(function(){
var clone = $(".displ").clone();
// query my json file
clone.find("#fblink").find("span").html(myJSON.FB);
clone.find("#twtlink").find("span").html(myJSON.Twit);
$(".displ").append(clone);
});
最佳答案
var myJSON = [
{
"ProdID": 204,
"Title": "The best basket in town",
"FB": 32,
"Twit": 45
},
{
"ProdID": 201,
"Title": "The best soap in the whole of US",
"FB": 23,
"Twit": 0
},
{
"ProdID": 103,
"Title": "Limited quantity only",
"FB": 12,
"Twit": 3
},
]
$(document).ready(function(){
var clone = $(".displ").clone();
var MYJSON = myJSON.find((elem)=>elem.ProdID=="103")
// query my json file
debugger; clone.find("#fblink").find("span").html(MYJSON.FB);
clone.find("#twtlink").find("span").html(MYJSON.Twit);
$(".displ").html(clone);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="displ">
<a class="button__link" id="fblink" target="_blank" aria-label="">
<div class="button--small"><div class="button__icon">
<span></span>
</div>
</div>
</a>
<a class="button__link" id="twtlink" target="_blank" aria-label="">
<div class="button--small"><div class="button__icon">
<span></span>
</div>
</div>
</a>
</div>
检查这是否是您想要做的。我添加了 prodID ==103 进行测试。
关于javascript - 查询 JSON 并检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48139672/