我想使用数组的值来填充网页。这些值应该替换跨度之间的文本(这已经工作了),但同时数组中的一些值应该用作属性和文件路径的一部分。最后,只有当值符合条件时才应该替换某些内容。
以各种方式插入数组数据-这是如何完成的?
这是HTML部分:
<p><b><span class="weather">weather here</span></b> and
<span class="temperature">temperature here</span>.</p>
<p><i><span class="color">color here</span></i>.</p>
Here follows is an image loaded according to the data
<img src="fixed_path#weather"></img>. And this should
have the proper <span color="#color">hue</span>.
<span class="warning"></span>
这是jQuery Javascript部分(jsfiddle链接在下面):
var arr = {
"weather": "cloudy",
"color": "#880000",
"temperature": "hot"
};
$.each(arr, function (key, value) {
$('.'+key).replaceWith(value);
// how to replace src path?
// how to replace text attribute?
// make the following conditional
// if($.inArray("temperature.hot", arr) > !=1) {
$('.warning').replaceWith('Warning!');
// }
});
jsFiddle链接
好了,我都想明白了。我了解到,我所处理的并不是一个真正的关联数组(它们不像Javascript中的字符串那样存在),而是对象和属性。因此,它们可以通过"objectname.property"来选择。
这是解决方案(jsFiddle可以在下面找到):
CSS:.colortext {
color: #00ff00;
}
HTML: <p><b><span class="weather">weather here</span></b> and
<span class="temperature">temperature here</span>.</p>
<p><i><span class="color">color here</span></i>.</p>
Here follows is an image loaded according to the data
<img src="" class="imagepath"></img>. And this should
have the proper <span class="colortext">hue</span>.
<span class="warning">No extreme weather.</span>
Javascript (jQuery): var arr = {
"weather": "cloudy",
"color": "#880000",
"temperature": "normal",
"imgagepath": "/path/to/image/"
};
$.each(arr, function (key, value) {
$('.'+key).replaceWith(value);
$('.imagepath').attr('src', arr.imagepath);
$('.colortext').css('color', arr.color);
if (arr.temperature == 'hot') {
$('.warning').replaceWith('Heat warning!');
}
if (arr.temperature == 'cold') {
$('.warning').replaceWith("It's freezing.");
}
});
jsFiddle