Skip to content Skip to sidebar Skip to footer

Insert Text, Attributes And Paths On Condition

I would like to use the values from an array to populate a web page. The values should replace text between spans (this already works) but at the same time some values from the arr

Solution 1:

OK, I've got it all figured out. I learned that what I am dealing with isn't really an associative array (they don't exist like that with strings in Javascript) but rather objects and properties. Therefore they can be selected with "objectname.property".

Here is the solution (jsFiddle can befound below):

CSS:

.colortext {
    color: #00ff00;
}

HTML:

<p><b><spanclass="weather">weather here</span></b> and 
<spanclass="temperature">temperature here</span>.</p><p><i><spanclass="color">color here</span></i>.</p>
Here follows is an image loaded according to the data
<imgsrc=""class="imagepath"></img>. And this should 
have the proper <spanclass="colortext">hue</span>.
<spanclass="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

Post a Comment for "Insert Text, Attributes And Paths On Condition"