我是web dev的新手,这是我在StackOverflow上的第一个问题。如果我没有正确构建它,请道歉。
这是我的json。
{
"books":
[
{
"_id": "1",
"book_cat": "OLD",
"book_eng_name": "Book1",
"chapter_count": "50"
},
{
"_id": "2",
"book_cat": "OLD",
"book_eng_name": "Book2",
"chapter_count": "40""
}
]
我想将这个带有jquery的json用于追加。首先,我需要过滤__id
,然后在<ul>
&#34; Chapter_count&#34;次。
例如,如果我选择我正在搜索_id 1
我想要50个项目列表
Chapter 1
Chapter 2
...
...
...
Chapter 50
我想在以下html中附加到ul:
<html>
<title>Chapters</title>
<body>
<ul></ul>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/
jquery.min.js"></script>
<script type = "text/javascript" src='files/js/Chapter_script.js'></script>
<script type = "text/javascript" src='files/js/books.json'></script>
</body>
</html>
我写了类似的东西,但没有工作:(
(document).ready(function(){
var search_id = window.location.search;
var chapter_no = search_id.match(/\d+/g);
$.getJSON("files/js/books.json",function(data){
$.each(data.books, function(){
if (this['_id'] == chapter_no ){
for(var i = 0; i <= this['chapter_count']; i++; ){
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}
};
})
});
});
使用window.location.search从url中提取chapter_no 示例网址:http://localhost:90/chapters.html?book_id=1
提前致谢。
答案 0 :(得分:0)
首先你的json无效且语法错误我认为真正的
json ={ "books": [ { "_id": "1", "book_cat": "OLD", "book_eng_name": "Book1",
"chapter_count": "50" }, { "_id": "2", "book_cat": "OLD",
"book_eng_name": "Book2", "chapter_count": "40" } ]}
其示例js代码
json.books.forEach(function (b){
if(b._identer code here == "1")
{
for(var i =0 ; i<=b.caphter_count;i++)
{
//put your code here
}
}
})
答案 1 :(得分:0)
将以下代码复制到$.getJSON("files/js/books.json",function(data)
功能。
var selectedElement = $.grep(data.books, function( element, index ) {
if(chapter_no == element._id)
return element
});
for(var i =0 ; i<=selectedElement[0].chapter_count;i++)
{
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}