简体   繁体   English

jQuery不更新DOM元素HTML

[英]jQuery not updating the DOM element HTML

I'm trying to do a up/down vote system, but when I get the response from the API, I can't seem to target the element I want, which is the span within li with a class of "score". 我正在尝试做一个向上/向下投票系统,但是当我从API获得响应时,我似乎无法定位到我想要的元素,这是li内“ score”类的范围。

My js handlers 我的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
    });
});

The html view that is trigging the event, and the "score" area that's under it. 触发事件的html视图及其下的“得分”区域。

        <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 is not a child of the obj . li.score不是obj的子级。 Given that object is actually the DOM object clicked on by passing $(this) to the function then I guess it should be: 给定该对象实际上是通过将$(this)传递给函数而单击的DOM对象,那么我想它应该是:

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

The issue is that obj is an Event object not your HTML element. 问题在于obj是一个Event对象,而不是您的HTML元素。 Also, there is no child method. 另外,没有child方法。 Use children : 使用children

Change this line: 更改此行:

vote(obj, post_id, 1);

to: 至:

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

This should pass the ul to your vote() function. 这应该将ul传递给您的vote()函数。

And change: 并更改:

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

to: 至:

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

obj是事件对象,这是您想要做的

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

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

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