.click()处理程序重新加载页面,而不是触发事件 [英] .click() handler reloading page instead of triggering event
问题描述
我正在使用CodeIgniter,并尝试实现jQuery/AJAX以在不刷新页面的情况下在我的网站上触发操作.只需将其喜欢的Facebook帖子和喜欢的按钮放上即可.
I'm using CodeIgniter and trying to implement jQuery/AJAX to fire actions on my site without refreshing the page. Simply put its like Facebook posts and the like button.
到目前为止,我设法整理了一个小的脚本来完成工作,只是每三次单击都会重新加载页面.
So far I managed to put together a small script that gets the job done except it reloads the page on every third click.
我将动作按钮封装在ID为'post_'
的div
+帖子的数据库id
中.
I enclosed the action buttons in a div
with an id 'post_'
+ the post's db id
.
然后我在单击的链接中添加了一个value属性,该链接保存了帖子ID,并且该类是这样的.
then I added a value attribute to the clicked link which holds the post id and the class is like.
<div>
<h3>User Name</h3>
<p>Post Content</p>
<div id="post_3">
<a href="#" class="like" value="3">Like</a>
<div>
</div>
$(".like").click(function(event){
var post = $(this).attr("value");
var mydv = "#post_"+post;
$.ajax({
type: "POST",
url: 'localhost/like/'+post,
success: function(response) {
if (response == "Success")
{
$(mydv).load("localhost/newsfeed"+mydv);
}
else
{
alert("Error");
}
}
});
event.preventDefault();
});
当页面在第三次单击时重新加载时,它只是一个简单的重新加载而没有反馈或触发过程.
When the page reloads on the third click, its just a simple reload no feedback or process fired.
我一定做错了,我只是不知道什么.
I must be doing something wrong, I just don't know what.
推荐答案
您要替换包含a.like
的div
的内容. click
处理程序将不会附加到由于load()
调用而添加的任何锚点.您需要使用事件委托:
You're replacing the contents of the div
which contains the a.like
. The click
handler will not be attached to any anchor's which are added as a result of the load()
call. You need to use event delegation:
$(document).on('click', '.like', function(e) {
e.preventDefault();
// your code
});
这篇关于.click()处理程序重新加载页面,而不是触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!