You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何JQuery无法从替换div传递post_id和post_type至视图?

解决点赞/取消点赞功能中post_id和post_type无法传递的问题

我看你这问题核心是两个点:动态替换HTML后事件绑定失效,还有用div的value属性存数据的方式不对,另外咱们可以把数据直接绑在按钮上,不用依赖额外的div,这样更稳妥。下面一步步给你解决:

1. 改用事件委托处理动态按钮的点击事件

原来的$(".like-post-btn").on('click', ...)只会给页面一开始就存在的按钮绑定事件,当你用AJAX把.like-stuff里的HTML替换掉后,新生成的按钮根本没绑定点击事件。得用事件委托,把事件绑在父元素或者document上,这样不管怎么替换DOM,新按钮都能触发事件:

修改handle_likes.js里的点击事件:

// 给like按钮绑定事件委托
$(document).on('click', '.like-post-btn', function(){
    console.log("Thing was clicked!"); //  sanity check
    // 用$(this)指代当前点击的按钮,避免类选择器选中多个元素
    const $currentBtn = $(this);
    if ($currentBtn.val() === "not-liked") {
        console.log($currentBtn.val());
        // 直接从按钮的data属性拿参数传给函数
        like_post($currentBtn.data('post-id'), $currentBtn.data('post-type'));
    } else if ($currentBtn.val() === "is-liked") {
        unlike_post($currentBtn.data('post-id'), $currentBtn.data('post-type'));
    }
});

// 同理处理dislike按钮
$(document).on('click', '.dislike-post-btn', function(){
    const $currentBtn = $(this);
    if ($currentBtn.val() === "not-disliked") {
        dislike_post($currentBtn.data('post-id'), $currentBtn.data('post-type'));
    } else if ($currentBtn.val() === "is-disliked") {
        undislike_post($currentBtn.data('post-id'), $currentBtn.data('post-type'));
    }
});

2. 把post_id和post_type绑定到按钮的data属性上

不用单独搞#post_id和#post_type这两个div了,直接把数据存在按钮的data-*属性里,点击按钮时直接从当前按钮拿数据,就不会因为HTML替换找不到元素了。

修改feed.html里的按钮:

<div class="like-stuff">
 {% if not request.user|user_liked_post:post %}
 <button class='like-post-btn' value="{{like_btn_val}}" data-post-id="{{post.id}}" data-post-type="{{post_type}}">
 <span class="glyphicon glyphicon-thumbs-up"></span> Like
 </button>
 {% else %}
 <button class='like-post-btn' value="{{like_btn_val}}" data-post-id="{{post.id}}" data-post-type="{{post_type}}">
 <span class="glyphicon glyphicon-thumbs-up"></span> Unlike
 </button>
 {% endif %}
 <div class="like-count">{{post.like_count}}</div>
 {% if not request.user|user_disliked_post:post %}
 <button class='dislike-post-btn' value="{{dislike_btn_val}}" data-post-id="{{post.id}}" data-post-type="{{post_type}}">
 <span class="glyphicon glyphicon-thumbs-down"></span> Dislike
 </button>
 {% else %}
 <button class='dislike-post-btn' value="{{dislike_btn_val}}" data-post-id="{{post.id}}" data-post-type="{{post_type}}">
 <span class="glyphicon glyphicon-thumbs-down"></span> Undislike
 </button>
 {% endif %}
 <div class="dislike-count">{{post.dislike_count}}</div>
 </div>

修改likes.html里的按钮(确保替换后的按钮也带data属性):

<div class="like-stuff">
 <button class='like-post-btn' value="{{like_btn_val}}" data-post-id="{{post_id}}" data-post-type="{{post_type}}">
 <span class="glyphicon glyphicon-thumbs-up"></span> {{like_btn}}
 </button>
 <div class="like-count">{{like_count}}</div>
 <button class='dislike-post-btn' value="{{dislike_btn_val}}" data-post-id="{{post_id}}" data-post-type="{{post_type}}">
 <span class="glyphicon glyphicon-thumbs-down"></span> {{dislike_btn}}
 </button>
 <div class="dislike-count">{{dislike_count}}</div>
 </div>

3. 修改AJAX函数,直接接收参数传递

原来的函数依赖外部div拿数据,现在改成直接接收参数:

function like_post(postId, postType){
 console.log("Like post called...") // sanity check
 console.log("Test JQuery like post..");
 console.log(postId, postType);
 $.ajax({
 url: "posting/liking_post/",
 data: {
 post_id : postId,
 post_type : postType
 },
 success: function(data) {
 console.log(data);
 $('.like-stuff').html(data);
 },
 error : function(xhr,errmsg,err) {
 $('#results').html("<div class='alert-box alert radius' data-alert>Please contact an admin; We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>");
 console.log(xhr.status + ": " + xhr.responseText);
 }
 });
};

function unlike_post(postId, postType){
 console.log("Unlike post called...") // sanity check
 console.log("Test JQuery unlike post..");
 console.log(postId, postType);
 $.ajax({
 url: "posting/unlike_post/",
 data: {
 post_id : postId,
 post_type : postType
 },
 success: function(data) {
 $('.like-stuff').html(data);
 },
 error : function(xhr,errmsg,err) {
 $('#results').html("<div class='alert-box alert radius' data-alert>Oops! Please contact an admin for we have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>");
 console.log(xhr.status + ": " + xhr.responseText);
 }
 });
};

为啥原来的方式不行?

  • div没有value属性:你用<div id="post_id" value="{{post_id}}">,但div元素本身不支持value属性,所以$("#post_id").val()会返回undefined。就算要存div里,也得用data-value或者读文本内容,但绑在按钮上明显更合理。
  • 事件绑定失效:动态生成的DOM元素不会继承原来的事件绑定,必须用事件委托才能让新按钮触发点击逻辑。

这么改完之后,不管是第一次点击还是替换HTML后的第二次点击,都能正确拿到post_id和post_type传到视图里了。

内容的提问来源于stack exchange,提问作者Trippy-Chords

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:42:47