我有一个我坚持的编程问题。我不确定从哪里开始这个。任何帮助或方向将不胜感激。
构建一个HTML页面,在浏览器窗口中为多个圈子设置动画。当用户点击或点击某个圆圈时,它应该会改变颜色。可以通过解析JSON文件找到圆圈数。
JSON文件包含以下内容:
$currentPostThumbnails = get_theme_support('post-thumbnails');
if(is_array($currentPostThumbnails)) {
add_theme_support( 'post-thumbnails', array_merge($currentPostThumbnails, array( 'mytype' )) );
}else{
add_theme_support( 'post-thumbnails', 'mytype');
}
我有一个可以使用JSON的URL,而不是使用该文件。
根据我的理解,我可以使用AJAX和jQuery通过使用类似的东西来解析JSON:
{"numOfCircles":33}
谢谢!
答案 0 :(得分:1)
按照以下步骤执行您的要求:
将<div>
class="container"
添加到您的HTML文件<body>
中,就像这样
<div class="container">
<!-- circles will be appended here -->
</div>
然后将这些规则添加到CSS
.circle{
width:30px;
height:30px;
background: red;
display: inline-block;
margin-right:3px;
border-radius:30px
}
.circle.blue{
background: blue;
}
第一条规则将属于班级circle
的所有元素设置为一行显示的红色小圆圈,而第二条规则则在添加blue
类时将它们设为蓝色。
最后使用此javascript代码并确保jquery链接到您的文档
$.getJSON('path/to/file.json', function(data) {
for(i=0; i<= data.numOfCircles; i++){
$('.container').append('<div class="circle"></div>');
}
});
$('body').on('click', '.circle', function(){
$(this).toggleClass('blue');
});
第一位代码是请求你的子文件并创建一个for循环的代码,循环的次数与json文件中写入的整数值的次数完全相同。对于每次迭代,它会将<div>
元素与class="circle"
附加到父<div class="content">
。
后半部分将类blue
切换(添加/删除)到单击的元素。
答案 1 :(得分:0)
让我向您介绍一下您自己提供的代码:
$.ajax({
type: 'GET', //AJAX is creating a new HTTP GET
// connection
url: 'JSON URL here', //That should be placed to
// this web address
data: { get_param: 'numOfCircles' }, //Fill the variable
// named "data" with the field numOfCircles
// From the data recovered on the address provided
dataType: 'json', // The data recovered on the address
// provided is of the type JSON
success: function (data) { //if the data from the address
// provided was successfully parsed, execute
// this function to the parameter data
$.each(data, function(index, element) { //for each item
// in the (possibly array object) variable "data",
// execute this function, that has as parameters
// the index and value of the (possibly an array)
// variable data. in other words, iterate the "data"
// array with this function
$('body').append( //JQUERY to append new objects to
// the body of the mother page
$('<div>', { text: element.name }) //content being
// appended, in this case, the name of the element
// currently being processed from the data array,
// the name of the first element of the JSON array recovered!
);
});
}
})
JSON是Web对象,计算机可以以共享网页的方式相互共享。 JSON数组是可以通过URL恢复的数据集合!上面的函数从URL获取JSON并对其内容执行某些操作,在您的情况下在页面上打印“num of circles”或“integer”或“33”。您需要创建一个for循环,将包含圆圈的新div添加到页面中33次,即JSON提供的数字33。这个数字应该在element.value中,其中element.name在代码中。