php - jQuery - <span> 返回 'undefined' 的 html

标签 php javascript jquery html

我正在尝试增加 <span> 的 html 值单击按钮时,jQuery 表示 <span> 的值未定义,即使页面上实际显示了一个数字。这是生成 HTML 的 PHP 部分:

echo '<div class="box" style="background-color:'.$colours[0].'">
      <p>'.$confessions[0].'<br></p><br>
      <div class="overlay"></div>
      <div class="slide">
        <div class="slideleft">#'.$ids[0].'</div>
        <div class="slideright">
            <span class="upvote" id="'.$ids[0].'">Upvote</span>
            <span class="counter" id="'.$ids[0].'">"'.$counter[0].'"</span>
        </div>
      </div>
      </div>'

这里是应该使 HTML 变魔术的 jQuery:

$("body").on("click", ".upvote", function(e) {
    $.ajax({
        url: 'vote.php',
        data: {
            type: 'up',
            id: $(this).attr('id')
        },
        type: 'post',
        success: function(data) {
            if (data == 'ok') {
                alert($(this).next().html());
            } else {};
        }
    });
});

它确实会在 upvote 时发出警报按钮被按下,但它的值为 undefined而不是实际数量。谁能阐明这个问题?

谢谢

最佳答案

$(this) 将不再包含被点击的元素,因为它在您的成功函数内超出范围,相反,您需要缓存该变量以便在您的成功函数内使用。

例如:

$("body").on("click", ".upvote", function(e){
    var clicked = $(this);
    $.ajax({ 
        url: 'vote.php',
        data: { type: 'up', id: clicked.attr('id') },
        type: 'post',
        success: function(data) {
            if(data == 'ok'){
                alert(clicked.next().html());
            } else {
            };
        }
    });   
});

关于php - jQuery - <span> 返回 'undefined' 的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092227/

相关文章:

php - 重写 url 在 htaccess 中不起作用

php - 如何在数据更改时更新 UI?

javascript - jquery ui slider 滑动后比较值

javascript - phonegap 中的数据库 View

javascript - FF JavaScript 问题

php - 如何检查字母在PHP中是大写还是小写?

php - mysql 用多个表搜索电子邮件和域名

javascript - 如何使用 Meteor 提供文件名中带有空格的静态图像?

javascript - Bootstrap v3.3.5和v2.1.1之间的Bootstrap折叠功能差异

javascript - html2canvas 没有得到图像全高