0

我想使用数组中的值来填充网页。这些值应该替换跨度之间的文本(这已经有效),但同时数组中的一些值应该用作属性和文件路径的一部分。最后,只有在值与条件匹配时才应替换某些内容。

以各种方式插入数组数据——如何实现?

这是 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 链接

4

1 回答 1

0

好的,我已经弄清楚了。我了解到我正在处理的并不是真正的关联数组(它们不像 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

于 2013-03-18T08:42:43.220 回答