0

こんにちは、画像セットのタイトルとソースから配列を作成したいと思います。次に、それをリストに追加し、配列をクリアして (セット内の画像が変更されます)、配列とリストをクリアします。セット内のイメージが変わるたびに、何度も繰り返します。

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;
}

これは単なるサンプルです。実際には、画像にはさらに多くのタグがあります。この関数が再度呼び出されたときにリストを空にする方法がわかりません。私は今コーディングを学んでいますが、これを修正して機能させる方法がわかりません。

4

1 に答える 1

0

これは私にはXY問題のように見えます。

上記のサンプルコードと前の質問から判断すると、既存の要素セットの属性に基づいてエントリのリストを更新しようとしていると思いますが、重複するタイトルのアイテムは1回だけ表示されます

私がそれを正しく理解したと仮定すると、これを行う1つの方法があります:(デモ: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;です。

于 2012-05-30T09:20:21.800 に答える