2013-03-17 72 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