1

我正在开始研究评级系统,并在我的 jquery 知识中发现了一个巨大的漏洞。到目前为止,我的代码是:

<script>

$(document).ready(function() {
    $("#rate").delegate("div","click", function() {
        var targetid = $(this).attr("id");
        var voteval = $( '#' + targetid + ' span').html(); 
        if(isNaN(voteval)) { var voteval = 0; }
        voteval++;
        $( '#' + targetid + ' span').text(voteval);
    });

});
</script>

它成功地在 #rate 组中找到了一个 div 的 ID,并在关联的 span 中操作了数据。

我的问题是我希望能够在包含某个类的组中找到 div。简而言之,当用户单击时,它将查找“.active”并将其删除,如果它存在,然后在“当前”目标(this)上插入 .active。

4

3 回答 3

0

我猜你想要这样的东西

$(document).ready(function () {

    $("#rate").on("click", "div", function () {
        //    get text of span and make it int, also init to 0 if it's not a number
        var thisTextToInt = parseInt($(this).children("span").text()) || -1;    
        //    increment the text and set it to the span
        $(this).children("span").text(thisTextToInt+1);    

        $('#rate .active').removeClass('active');    //    remove previous active
        $(this).addClass('active');                  //    make this active
    }); 

});

虽然,我必须说这不是将文本设置为元素的好方法。最好将数据保存在其他地方,并将它们绑定到视图元素,以便它们自动更新。

于 2013-06-30T19:55:18.423 回答
0

您可以在点击事件中简单地执行此操作:

$('.active').removeClass('active');
$(this).addClass('active');

如果一个类活动存在,它将删除它。

如果你有多个#rate,那么你需要像这样找到最接近的(它应该是类而不是 id):

var $parent = $(this).closest('#rate');
$parent.find('.active').removeClass('active');
$(this).addClass('active');
于 2013-06-30T19:46:20.163 回答
0

您可以从其他人那里删除活动课程并div像这样添加到当前课程

$("#rate div").removeClass('active');
$(this).addClass('active');
于 2013-06-30T19:48:33.893 回答