2012-05-30 30 views
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; 
} 

這只是一個樣本。實際上圖像有更多的標籤。當我再次調用這個函數時,我不知道如何清空列表。即時通訊只是現在學習編碼,我不知道如何糾正這一點,使其工作。

+2

'title_array = src_array = [];' – zerkms

+0

只要把title_array = [];和src_array = [];在函數內部,所以每次函數觸發數組重置。 也使用$ .unique()清除重複的DOM元素。請看這裏 http://api.jquery.com/jQuery.unique/ – 2012-05-30 08:24:26

+0

@zerkms。你可以用'arr.length = 0' [DEMO](http://jsfiddle.net/yhPYa/)和[MDN](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects /陣列/長度) – gdoron

回答

0

這在我看來像一個XY problem

從您的示例代碼來看上面還有你的previous question,我猜正在試圖做的是更新基於現有的一組元素的屬性條目列表,但與項目重複的標題只顯示一次。

假設我說對了,這裏是應該做的一種方式:(演示:http://jsfiddle.net/SxZhG/2/

var $imgs = $("#imageholder"), $list = $("#list"); 

function summary_change() { 
    // store data in tmp obj with title as key so we can easily ignore dups 
    var store = {}; 

    $imgs.find("img").each(function() { 
     if (store.hasOwnProperty(this.title)) return; // ignore dup title 
     store[this.title] = this.getAttribute("src"); 
    }); 

    $list.empty(); // empty the list 
    for (var title in store) { // add new list items 
     $("<li>") 
      .append($("<div>", {"text":title})) 
      .append($("<img>", {"src":store[title]})) 
      .appendTo($list); 
    } 
} 

需要注意的是,如果一個以上的圖像具有相同的標題,只有第一個的src使用在總結結果中。如果你想使用找到的最後一個項目的src,簡單地刪除行if (store.hasOwnProperty(this.title)) return;

相關問題