将条件文本,属性和路径 [英] Insert text, attributes and paths on condition

查看:178
本文介绍了将条件文本,属性和路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的值从一个数组来填充网页。值应该更换跨度之间的文本(这已经作品),但在同一时间从所述阵列的一些值应作为属性和作为文件路径的一部分。最后,事情应该只更换当值的条件相匹配。

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.

插入以各种方式阵列中的数据 - 这可怎么完成

这是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低于):

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

推荐答案

好了,我把一切都想通了。我了解到,我所处理的是不是一个真正的关联数组(它们不存在一样,在JavaScript中的字符串),而是对象和属性。因此它们可与objectname.property来选择。

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

下面是解决方案(的jsfiddle可以在下面下找到):

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的):

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

这篇关于将条件文本,属性和路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆