gpt4 book ai didi

javascript - ajax 调用后 jQuery 不工作,即使我使用了正确的 on() 方法

转载 作者:行者123 更新时间:2023-11-30 15:14:57 25 4
gpt4 key购买 nike

我正在使用 django-el-pagination,一个 django package that allows ajax pagination .我正在对 Comment(评论列表)的查询集进行分页。查询集在 comments.html 中,在 comments_base.html 中,在 article.html(父 View )中。这是我的观点:

def article(request, category, id, extra_context=None):
name = resolve(request.path).kwargs['category']
instance = get_object_or_404(Post, id=id, entered_category=name)

new_comments_list = Comment.objects.filter(destination=id, parent_id=0).order_by('-timestamp')

template = 'article.html'
page_template = 'comments.html'

if request.is_ajax():
template = page_template

context = {
'id': id,
'comment_list': new_comments_list,
'page_template': page_template,
'instance': instance,
}
if extra_context is not None:
context.update(extra_context)
return render(request, template, context)

comments_base.html

{% block comments_base %}

<div class="commentsContainer">
<div class="endless_page_template">
{% include 'comments.html' %}
</div>
{% block js %}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{% static 'js/el-pagination/js/el-pagination.js' %}"></script>
<script>
$.endlessPaginate({
});
</script>
{% endblock %}
</div>

{% endblock %}

comments.html

{% block comments %}

{% paginate 10 comment_list %}
{% for i in comment_list %}
{% if i.parent_comment %}
<div class="comment_shell hasParent">
{% else %}
<div>
{% endif %}
<div class='comment_div' data-comment_id="{{ i.id }}">
<div class="left_comment_div">
<div class="username_and_votes">
<h3><a class='username_foreign'>{{ i.user }}</a></h3>
{% for j in i.score.all %}
<span class="upvotes">{{ j.upvotes }}</span>
<span class="downvotes">{{ j.downvotes }}</span>
{% endfor %}
</div>
<br>
<p>{{ i.comment_text }}</p>
</div>
</div>
{% include 'comments.html' with comment_list=i.replies.all %}
</div>

{% endfor %}
{% show_pages %}


{% endblock %}

所以当我转到分页中的下一组评论时,jQuery 不起作用。我认为这是因为它被附加或动态内容。所以我使用了 on() 方法 which other answers say to do .但是它仍然不起作用。我将仅展示一个简单的示例来说明它不起作用:

$('.upvotes').on('click', function() {
$(this).css('color', '#fff');
});

点击时不改变颜色。那么,是否有任何原因导致它仍然无法正常工作,我该如何解决?

最佳答案

这听起来像是使用附加选择器参数的 jquery 的 on 方法重载的应用:

.on( events [, selector ] [, data ], handler )

来自 jquery 文档:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector.

所以这应该可行:

$('body').on('click', '.upvotes', function() {
$(this).css('color', '#fff');
});

或者在执行 javascript 时使用 DOM 中存在的任何其他元素代替“body”选择器。

关于javascript - ajax 调用后 jQuery 不工作,即使我使用了正确的 on() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44610434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com