0

Javascript/Jquery でやりたいことは、ボタン (各項目のボタン) をクリックして配列に追加できるようにすることです。お気に入りページをクリックすると、この配列が順番に投稿されます。

これがどのように機能するかについて頭を悩ませているだけです。配列内の各項目に、項目を説明する画像やテキストなど、いくつかの項目を含めることが必要な場合があるためです。

一般的な用語/例では、これはどのように設定されますか?

4

1 に答える 1

1

There are a number of ways to do this. But, I'll go with one that's a bit more general - which you can extend for yourself:

http://jsfiddle.net/TEELr/11/

HTML: This simply creates different elements with the favorite class - which will be the selector by which we check if an element has been clicked.

<div class="favorite"><p>Add to favorites</p></div>
<div class="favorite type2"><p>Just another favorite type</p></div>

<button id="reveal">
    Reveal Favorites
</button>

JS:

Every time an element with the "favorite" CSS class is clicked, it is added to the array - this also works for elements with more than one class (that have the "favorite" CSS class).

Now, when the "Reveal Favorites" button is clicked, it will alert what's in the array - which is in the order clicked (as asked).

$(document).ready(function() {
    var favorites = [];
    var counter = 0;

    $('.favorite').click(function() {
        ++counter;
        favorites.push("\"" + $(this).text() + " " + counter + "\"");
    });

    $('#reveal').click(function() {
       alert(favorites); 
    });
});

CSS:

Simple CSS that only exist for demonstration purposes to prove previous point with multiple CSS class selectors:

.favorite {
    width: 400px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    display: block;
    background-color: #f3f3f3;
    border-bottom: 1px solid #ccc;
}

.favorite.type2 {
    background-color: #ff3;
}

.favorite:hover {
    cursor:hand;
    cursor: pointer;
}
于 2013-03-11T22:01:02.697 に答える