isNan 在 jQuery 中将此选择器与动态内容一起使用

isNan using this selector with dynamic content in jQuery

本文关键字:动态 一起 选择器 jQuery isNan      更新时间:2023-09-26

这是我尝试使用的函数

$('body').on('click', '.up-vote', function(event) {
    event.preventDefault();
    var data = {"action": "voteKarma", "id": $(this).data("id"), "value": $(this).data("val")}
    $.post(window.apiURL, data, function(result) {
        switch(result['status']) {
            case 1:
                var vote_sum_text = $(this).next(".sum").text();
                if (!isNaN(parseInt(vote_sum_text, 10))) {
                    var vote_sum_text = $(this).next(".sum").text();
                } else { alert("isNaN Variable") } 
            break;
    }, 'json');
});

当 Ajax 结果返回 0 时,它返回带有 isNaN 变量的警报,这是我调试问题的后备。

这是我的HTML布局,它是使用另一个Ajax请求动态抓取的,其中多个div以<li>格式列出:

<div class="votes pull-left">
    <a class="up-vote" href="#" data-id="20" data-val="1"><span class="fa fa-arrow-circle-o-up"></span></a>
    <span class="sum" style="font-weight:400;color:#666;">
         0
    </span>
    <a class="down-vote" href="#" data-id="20" data-val="0"><span class="fa fa-arrow-circle-o-down"></span></a>
</div> 

简单来说;当你单击.up-vote.down-vote时,它将发送一个AJAX请求,然后获取.sum值的text()

尝试使用

$(event.currentTarget).next(".sum").text();

因为.post中的this不是指元素

您还可以使用以下方法:

$('body').on('click', '.up-vote', function(event) {
   event.preventDefault();
   var up_vote_this = $(this);
   ....
   ....
   //now you can use the variable in the success function...
      var vote_sum_text = up_vote_this.next(".sum").text();