0
您好,我想從圖像集的標題和src中創建一個數組。然後將其附加到列表中,然後清除數組(集中的圖像更改),然後清除數組和列表。隨着圖像中的圖像變化,一次又一次地重複它。如何從數組中追加內容,然後在jQuery中清除它
下面是HTML:
<div id="imageholder">
<img src="images/a001.png" title="orange"/>
<img src="images/a002.png" title="red apple"/>
<img src="images/a003.png" title="green apple"/>
<img src="images/a004.png" title="red apple"/>
</div>
<ul id="list"></ul>
這裏是代碼:
title_array = [];
src_array = [];
function sumarychange() {
$("#imageholder img").each(function() {
// pushing each values into arrays
title_array.push($(this).attr("title"));
src_array.push($(this).attr("src"));
// i think this part will append the content in the arrays
var list = $('#list');
var existing_item = $('#list_'+ title);
// removing items with the same titles
if (existing_item.length < 1){
var new_item = $('<li />');
new_item.attr('id', 'list_'+ title);
new_item.html('<div>' + title + '</div><img src="' + src + '" />');
list.append(new_item);
}
});
// i think this will set the arrays back to empty
title_array.length = 0;
src_array.length = 0;
}
這只是一個樣本。實際上圖像有更多的標籤。當我再次調用這個函數時,我不知道如何清空列表。即時通訊只是現在學習編碼,我不知道如何糾正這一點,使其工作。
'title_array = src_array = [];' – zerkms
只要把title_array = [];和src_array = [];在函數內部,所以每次函數觸發數組重置。 也使用$ .unique()清除重複的DOM元素。請看這裏 http://api.jquery.com/jQuery.unique/ – 2012-05-30 08:24:26
@zerkms。你可以用'arr.length = 0' [DEMO](http://jsfiddle.net/yhPYa/)和[MDN](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects /陣列/長度) – gdoron