条件插入文本,属性和路径

时间:2013-03-17 16:27:50

标签: javascript jquery attributes replace conditional

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

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

这是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 link

1 个答案:

答案 0 :(得分: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