繁体   English   中英

各个div的jquery函数

[英]jquery function for individual divs

我认为可以使用.prev()函数来实现,但是由于某些原因,它无法正常工作。

我正在为博客上的帖子创建拇指向上/向下按钮。 我正在尝试根据用户的投票显示消息。 UP或DOWN,但是每当我投票1条特定帖子时,该帖子就会出现在所有帖子中。

这是我的代码。 我删除了prev()使其更具可读性的尝试。 该脚本在ajax方面运行良好。

$(document).ready(function() {
    $(".vote_button").click(function(e) { //the UP or DOWN vote button
    var vote_status = $(this).attr('class').split(' ')[1]; //gets second class name following vote_button
    var vote_post_id = $(this).attr("id"); //the post ID
    var dataString = 'post_id=' + vote_post_id + '&vote_status=' + vote_status;

    $.ajax({
        type: "POST",
        url: "url/add_vote.php",
        data: dataString,
        cache: false,
        success: function(html) {
            if (vote_status == 1) 
         {
                $('.msg_box').fadeIn(200);
                $('.msg_box').text('You voted UP!');
            }
            if (vote_status == 2) 
         {
                $('.msg_box').fadeIn(200);
                $('.msg_box').text('You voted DOWN!');
            }
        }
    });
    return false;
});
});

范例HTML

<div class="vote_button 1" id="18">UP</div>
<div class="vote_button 2" id="77">DOWN</div>
<div class="msg_box"></div>

<div class="vote_button 1" id="43">UP</div>
<div class="vote_button 2" id="15">DOWN</div>
<div class="msg_box"></div>


<div class="vote_button 1" id="11">UP</div>
<div class="vote_button 2" id="78">DOWN</div>
<div class="msg_box"></div>

编辑:提供的jsfiddle没有Ajax部分http://jsfiddle.net/XJeXw/

您需要在click处理程序中保存对按钮的引用(例如, var me = $(this); ),然后在AJAX处理程序中使用me.nextAll('.msg_box:first')

编辑示例

var me = $(this);   //The this will be different inside the AJAX callback

$.ajax({
    type: "POST",
    url: "url/add_vote.php",
    data: dataString,
    cache: false,
    success: function(html) {
        me.nextAll('.msg_box:first')
            .text(vote_status == 1 ? 'You voted UP!' : 'You voted DOWN!')
            .fadeIn(200);
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM