Javascript jQuery on click using.before()
我有一个方法,它执行一些ajax,结果是在一个div之前创建一个新的div,然后在其中插入ajax响应。我遇到的问题是,在('click')上使用时,我的第二次单击在先前创建的div(我想要的)之前追加了一个新div,但在之后(不是我想要的)创建了另一个完全相同的div AJAX/jQuery:Javascript jQuery on click using.before(),javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,我有一个方法,它执行一些ajax,结果是在一个div之前创建一个新的div,然后在其中插入ajax响应。我遇到的问题是,在('click')上使用时,我的第二次单击在先前创建的div(我想要的)之前追加了一个新div,但在之后(不是我想要的)创建了另一个完全相同的div AJAX/jQuery: $(document).on('click', '.ajaxcommentbutton1', function() { var currentDiv, pageValue, newPage, newPa
$(document).on('click', '.ajaxcommentbutton1', function() {
var currentDiv, pageValue, newPage, newPageid;
currentDiv = $(this).attr('group');
pageValue = parseFloat($(this).attr('data'));
newPage = pageValue + 1;
newPageid = '.' + newPage;
$.ajax({url:"comments.php",
type:'POST',
dataType:'text',
data: {id: currentDiv,
page: newPage},
success:function(result){
$('div[data="' + currentDiv + '"] .commentsContainer > div').before("<div class='" + newPage + "'> </div>");
$('div[data="' + currentDiv + '"] ' + newPageid).html(result);
$('button[group="' + currentDiv + '"]').attr('data', newPage);
$('button[group="' + currentDiv + '"]').off();
}});
});
$(文档).on('单击','.ajaxcommentbutton1',函数(){
var currentDiv、pageValue、newPage、newPageid;
currentDiv=$(this.attr('group');
pageValue=parseFloat($(this.attr('data'));
newPage=pageValue+1;
newPageid='.'+newPage;
$.ajax({url:comments.php“,
类型:'POST',
数据类型:'text',
数据:{id:currentDiv,
页码:newPage},
成功:功能(结果){
$('div[data=“'+currentDiv+']”。commentsContainer>div')。在(“ ”);
$('div[data=“”+currentDiv+“]'+newPageid.html(结果);
$('button[group=“”+currentDiv+“]”)attr('data',newPage);
$('button[group=“”+currentDiv+'“]).off();
}});
});
第一次单击的HTML结果:
<div class='commentsContaier'>
<div class="2">stuff in here</div>
<div class="1">stuff in here</div>
</div>
这里的东西
这里的东西
第二次单击的HTML结果(错误):
这里的东西
这里的东西
这里的东西
这里的东西
因为$('div[data=“'+currentDiv+'].commentsContainer>div')
匹配容器下的每个
,并将您的AJAX内容添加到每个匹配的
,复制您的AJAX内容
i、 e.在第二次单击中,新元素被插入到此处的填充中
和此处的填充中
尝试将其替换为$('div[data=“'+currentDiv+'].commentsContainer>div:first child')
以仅匹配所有
的第一个子项,并使用选择器
<div class='commentsContaier'>
<div class="3">stuff in here</div>
<div class="2">stuff in here</div>
<div class="3">stuff in here</div>
<div class="1">stuff in here</div>
</div>