Javascript AJAX第二次调用不';行不通
我试图做一个简单的投票按钮,但它的作品只有一次每后每次重新加载 它应该如何工作: 单击“+”->更新查询(在django中)->重新加载一个div(将“+”更改为“-”)->允许单击“-”撤消升级投票 它在我第一次投票后显示“-”按钮,但当我点击它时,什么也没有发生。只有当我点击“F5”并重新加载页面时,它才起作用 控制台中没有错误Javascript AJAX第二次调用不';行不通,javascript,jquery,ajax,Javascript,Jquery,Ajax,我试图做一个简单的投票按钮,但它的作品只有一次每后每次重新加载 它应该如何工作: 单击“+”->更新查询(在django中)->重新加载一个div(将“+”更改为“-”)->允许单击“-”撤消升级投票 它在我第一次投票后显示“-”按钮,但当我点击它时,什么也没有发生。只有当我点击“F5”并重新加载页面时,它才起作用 控制台中没有错误 ... some django scripts to check which button should be displayed ...
... some django scripts to check which button should be displayed ...
<span class="upvote"><span postId="{{post.id}}" class="vote" href="upvote/{{post.id}}">+</span></span>
<span class="downvote"><span postId="{{post.id}}" class="vote" href="downvote/{{post.id}}">-</span></span>
...
$(document).ready(function(){
$(".vote").click(function(e){
href = $(this).attr("href");
postId = $(this).attr("postId");
$.ajax({
url: href,
success: function() {
$("#post-"+postId+" >header").load(location.href+ " #post-"+postId+">header>*");
},
});
});
。。。一些django脚本来检查应该显示哪个按钮。。。
+
-
...
$(文档).ready(函数(){
$(“.vote”)。单击(函数(e){
href=$(this.attr(“href”);
postId=$(this.attr(“postId”);
$.ajax({
url:href,
成功:函数(){
$(“#post-”+postId+“>header”).load(location.href+“#post-”+postId+“>header>*”);
},
});
});
“posted”和“href”属性已正确填充。根据您发布的代码,问题并不明显,但我猜,
-
是在您单击+
后添加到DOM中的。如果是这样,那么您的问题是您只绑定了$('.vote')。on(“单击”…
到.vote
元素,当该代码首次在页面加载时在DOM中执行。您可以通过使用事件委派将事件处理程序绑定到静态父元素并对来自与选择器匹配的子元素的任何事件执行操作来解决此问题:
$(document).on('click', ".vote", function(e){
href = $(this).attr("href");
postId = $(this).attr("postId");
$.ajax({
url: href,
success: function() {
$("#post-"+postId+" >header").load(location.href+ " #post-"+postId+">header>*");
},
});
})
为什么不在页面周围使用标记,并使用href to?它可以很好地使用,但页面每单击2次就会滚动到顶部。这可能是我将其更改为的原因,因此如果有办法,我希望继续使用它。请尝试放置
$(“.vote”)。单击()
在$(文档)之外处理事件。就绪()
context.还是一样,没有任何变化