Javascript 附加到最近的div
如何将数据插入Javascript 附加到最近的div,javascript,jquery,html,Javascript,Jquery,Html,如何将数据插入,使其不附加到“reply\u form”类的每个实例中 {% for comment in comments %} {{comment.name}} <p>{{comment.text}}</p> <div class = "buttonDisplayForm" data-path={{path("new", {'blog_id' : BlogPost.id})}} data-id= {{comment.id}}>
,使其不附加到“reply\u form”
类的每个实例中
{% for comment in comments %}
{{comment.name}}
<p>{{comment.text}}</p>
<div class = "buttonDisplayForm" data-path={{path("new", {'blog_id' : BlogPost.id})}} data-id= {{comment.id}}>
<button type="button" class="btn btn-primary">Reply</button>
</div>
<div class="reply_form"></div>
{% endfor %}
我想用它添加表单,
empty()
通过多次单击按钮来防止添加更多表单,但这也会将表单字段添加到每个reply\u表单
元素。您必须存储当前对象$(此)
在变量中,这样您就可以在成功回调中使用它来引用相关的回复表单
,单击按钮显示表单
按钮:
$(".buttonDisplayForm").on('click', function() {
var _this = $(this);
...
success: function(data){
$(".reply_form", _this).empty().append(data);
}
完整代码:
$(document).ready(function(){
$(".buttonDisplayForm").on('click', function() {
var path = $(this).attr('data-path');
var _this = $(this);
$.ajax({
type: 'POST',
cache: false,
url: path,
success: function(data){
$(".reply_form", _this).empty().append(data);
}
});
});
});
注意:我们将$(this)
对象存储在回调之外,因为它在回调中是不同的,而是指Ajax调用的jqXHR
对象
希望这能有所帮助。很有效,谢谢。为什么$(这个)在ajax成功中不起作用?我想使用
$(this)
,但我不明白为什么它不起作用。因为在回调中,this
引用Ajax调用的jqXHR对象,而不是事件处理程序绑定到的元素。不客气,很高兴我能帮上忙。愉快的编码。我在OP中编辑了HTML。问题是,如果
在按钮显示表单
div中,那么当我单击表单的文本字段时,它会触发JS,我希望只有在单击回复按钮后才会触发它。现在reply\u表单
不在this
中,所以我尝试使用最近(“.reply\u表单”)
,但这不起作用。有什么想法吗?谢谢你。下一步(“.reply\u form”)。因为现在重播表单如果只是按钮的下一个,我就这样使用它$(\u this).next(“.reply\u form”).empty().append(data)代码>并且它什么都不做。
$(document).ready(function(){
$(".buttonDisplayForm").on('click', function() {
var path = $(this).attr('data-path');
var _this = $(this);
$.ajax({
type: 'POST',
cache: false,
url: path,
success: function(data){
$(".reply_form", _this).empty().append(data);
}
});
});
});