我的页面上有一个视频缩略图,带有一个小图标“拇指朝下”。当您单击该缩略图时,会显示另一个缩略图,替换另一个缩略图。用户可以按照自己的意愿进行操作。
我的代码现在只能在第一次运行。 HTML:
<a href="/change/videos/{{ video.video_id}}/thumbsdown/" data-sort="sort" data-page="page" class="dislike_black" title="I dislike this"></a>
AJAX:
$('.dislike_black').click(function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
当我第一次单击该图标时,一切正常,触发警报,第二次单击该图标时,没有警报,并且浏览器正在加载 href 链接。
我尝试过.preventDefault();成功并完成了事件,但它不起作用。
关于如何执行此操作有任何提示吗?
最佳答案
您的内容是动态创建的,因此,根据您使用的 jQuery 版本,您需要 jQuery.live()
或 jQuery.on()
方法
jQuery.live() since jQuery 1.3 an event handler for all elements which match the current selector, now and in the future.
jQuery.on() since jQuery 1.7 - Attach an event handler function for one or more events to the selected elements.
示例
jQuery.live()
$('.dislike_black').live("click", function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
jQuery.on()
$('.dislike_black').on("click", function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
更多信息
关于Ajax - 阻止点击成功的 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9039948/