1

私は Facebook の受信トレイのような左ナビゲーション リンクを作成しようとしています。div には 3 つの違いがあります。 1. 未読 (水色) 2. 既読 (白) 3. 選択済み (濃青)

通常の方法で行うと、実際には非常に簡単です。つまり、クリックして各メッセージを読むたびに、ページをリロードする必要があります。

でも今回は完全にajaxでやりたい。私はすべての仕事をしました。しかし、最後のステップで問題を解決してください。

アイデアは: Cookie (jquery.cookie プラグイン) を使用して、最後にクリックされた Div Idを保存します。メッセージを読むたびに div をクリックすると、最後にクリックされた div idは白に変わる必要があります。(メッセージが読まれたため)。

未読メッセージのDivをクリックすると。問題があります: 未読メッセージの Div が再び水色に変わります

通常の JavaScript と jQuery の両方で多くのメソッドを使用します。

まず、私の div を見てみましょ う:

<div id ='001' class='normal' onclick=readmsg(id_msg1)></div>
<div id ='002' class='normal' onclick=readmsg(id_msg2)></div>
<div id ='003' class='normal' onclick=readmsg(id_msg3)></div>

JavaScriptで

function readmsg(id_msg) // or 2 or 3 & so on .....


 $.cookie('last_read', id_msg1);// set cookie at once



document.getElementById(id_msg1).className = "inbx_selected"; // div clicked just now--> selected:let´s say dark blue./// I have no problem with this.

これは、未読のクラスを読み取り済みのクラスに変更するために試したすべてです。

var ck= $.cookie('last_read');  

    $("#"+id_msg).addClass('inbx_unread'); // 

    $("#"+last_read).removeClass('inbx_unread');// get the last ID of clicked div and remove class unread which´s light-blue

次のような通常のJavaScriptも試しました。

document.getElementById(last_read).className.replace("inbx_unread","");

// ここにさらにコードがありますが、上で述べたように、それで終了しました。唯一の問題は、他のdivをクリックした後、未読(水色)が再び水色に戻ることです。

firebug とアラートをチェックインしました。正しい値が得られます。

Cookie のように一時的なデータを保存する他の方法を知りません。

質問を短くするには、別の div をクリックした後、クリックされた未読の Div を停止して元のクラスに戻すにはどうすればよいですか?

4

1 に答える 1

2

ここでは、少し異なるアプローチを示します。jQuery イベントのみを使用できます。

HTML

<div id ='001' class='message unread'>Message 1</div>
<div id ='002' class='message unread'>Message 2</div>
<div id ='003' class='message unread'>Message 3</div>

そしてjQuery:

$(document).ready(function(){

    $(".message").click(function() {

        // we get the clicked element ID
        var id_msg = $(this).attr('id');

        // we read the cookie, to remove the previous selected class to the last_read element
        var last_read = $.cookie('last_read');
        $('#' + last_read).removeClass("inbx_selected");

        // we set the cookie, so we keep can remove the selected class in the next click
        $.cookie('last_read', id_msg);

        //
        // probably, here you should do some AJAX post to update the message status at the database
        // 

        // we remove the unread class, and add teh selected class
        $(this).removeClass("inbx_unread").addClass("inbx_selected");

    });

});

動作中の jsfiddle を確認できます: http://jsfiddle.net/QaMJZ/1/

それが役に立てば幸いです、頑張ってください!

于 2013-09-03T02:16:27.683 に答える