2013-03-17 52 views
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 link

+0

你需要改变你的数组中元素的结构。在这种情况下,应该如何确定“文本”的含义? – Bergi 2013-03-17 16:48:17

+0

我改变了阵列。问题保持不变。我猜有条件的插入不会这样工作,因为关联(字符串)数组在JavaScript中是未知的。对于其他的事情,我仍然在寻找答案。 – PiEnthusiast 2013-03-17 20:16:51

+0

它和以前一样工作(虽然它不再是一个数组,而是一个无序的对象)。而且在结构中还没有关于是否改变'src','color'或'textContent'属性的信息。 – Bergi 2013-03-17 20:31:50

回答

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

0

这是repleace代码的图像的src路径

$("img").attr("src", "/path/to/the/img.ext"); 

改变.warning语句的内容就够用了:

$(".warning").text("plain text here") 
如果你想使用HTML标签,而不是纯文本的使用 .html()代替 .text()

我不能帮你与第三

问题,因为我不了解你想获得的条件。阅读后,再读一遍,也许它可能是:

if (arr.temperature == 'hot') { 
    // stuff 
} 
+0

谢谢。如何选择特定的值有所帮助。 – PiEnthusiast 2013-03-18 08:45:58