Insert text, attributes and paths on condition

2019-09-05 09:49发布

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 array should be used as attributes and as part of a file path. Lastly, something should be only replaced when a value matches a condition.

Inserting array data in various ways - how can this be accomplished?

This is the HTML part:

<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>

And this is the jQuery Javascript part (jsfiddle link is below):

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条回答
男人必须洒脱
2楼-- · 2019-09-05 10:03

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><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

查看更多
登录 后发表回答