jQuery没有更新DOM元素HTML

jQuery not updating the DOM element HTML

本文关键字:元素 HTML DOM 更新 jQuery      更新时间:2023-09-26

我试图做一个向上/向下投票系统,但是当我从API得到响应时,我似乎无法针对我想要的元素,这是具有"得分"类的li内的跨度。

我的js处理程序

    jQuery(document).ready(function($) {
    function vote(obj, post_id,vote) {
        if(vote && post_id) {
             $.get('/ajax/vote', { 
                v: vote,
                p: post_id
                }, function(data){
                    //set the .score to the new count returned by API
                    console.log(data);
                    $(obj).child('li.score').html(data.votes);
             });
        }
    }
    $(document.body).on("click", ".upvote", function(obj){ 
        console.log("Up Voted");
        var post_id = $(this).closest(".card").prop('id').replace(/post-id-/, '');
        vote(obj,post_id,1); 
    });
    $(document.body).on("click", ".downvote", function(){
        console.log("Down Voted");
        // more to come
    });
});

触发事件的html视图,以及它下面的"score"区域。

        <div class="vote-controls col-xs-1">
        <ul>
            <li class="upvote"><a href="#" class="disable"><span class="fa fa-angle-up "></span><span class="sr-only">&uarr;</span></a></li>
            <li class="downvote"><a href="#" class="disable"><span class="fa fa-angle-down"></span><span class="sr-only">&darr;</span></a></li>
            <li class="score"><span>0</span></li>
        </ul>
    </div>

li.score不是obj的子节点。鉴于该对象实际上是DOM对象点击通过传递$(this)函数然后我想它应该是:

$(obj).parent('ul').children('li.score').html(data.votes);

问题是objEvent对象而不是您的HTML元素。此外,没有child方法。使用children:

改变这一行:

vote(obj, post_id, 1);

:

vote($(this).parents('ul'), post_id, 1);

这将把ul传递给vote()函数。

和变化:

$(obj).child('li.score').html(data.votes);

:

$(obj).children('li.score').html(data.votes);

obj是事件对象,下面是你想做的

$(obj.currentTarget).siblings('li.score').find('>span').text(html.votes);