jQuery / AJAX - 盯着和不主演

时间:2013-01-26 03:52:32

标签: jquery html ajax

我希望能够为任何给定的对话(例如Gmail)加注星标/取消星标。当我点击“空”星标记重要内容时,我需要提交一些ajax,然后切换到明星形象。反之亦然,当我点击一个已加星标的对话时,我需要ajax提交并在其成功后,然后让“空”明星切换回来。

一些HTML(简而言之):

 <div class='__conversation'>
      <div class='__conversation_star'>
         <img class='__star_n' src='p_star_n.png'/>
         <img class='__star_y' src='p_star_y.png'/>
      </div>
 </div>

具有与基本功能类似的功能:

    $(".__conversation_star").click(function() {
         $(this).find('img').toggle();
    });

一些ajax:

 $(".__conversation_star").click(function() {
    jQuery.ajax({
        type: 'POST',
        url: "./process.conversation.php,
        data: {method: 'star'},
        cache: true,
        success: function() {
            // Toggle to un-starred .__star_n
        }
    });
 });

 $(".__conversation_star").click(function() {
    jQuery.ajax({
        type: 'POST',
        url: "./process.conversation.php",
        data: {method: 'star'},
        cache: true,
        success: function() {
            // Toggle to starred .__star_n
        }
    });
 });

有没有办法可以在ajax成功时执行切换?和/或其他哪些方法可以更好地运作?

谢谢!

1 个答案:

答案 0 :(得分:1)

不是切换哪个图像显示,而是切换CSS类可能更容易。因此,如果您的HTML设置如下:

<div class="conversation">
    <span class="star"></span>
    <span>blah blah blah blah</span>
</div>

然后你有了以下CSS:

.conversation{
    padding:3px 5px;
    border: 1px solid #CCC;
    margin-top:3px;
}

.star{
    background-color: hsl(200, 90%, 90%);
    border:1px solid #333;
    display:inline-block;
    height:20px;
    width:20px;
}

.star.state-selected{
    background-color: hsl(60, 70%, 60%);
}

现在,您只需在每个state-selected上切换课程<span class='star'>

以下是一些示例JavaScript

$(".star").click(function() {
    var $thisStar = $(this);

    $.ajax({
        type: 'POST',
        url: "./process.conversation.php",
        data: {method: 'star'},
        cache: true,
        success: function() {
            $thisStar.toggleClass("state-selected");
        }

    });

});

DEMO:http://jsfiddle.net/fbvg9/