我正在尝试增加 <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/