使用 jQuery ReplaceWith 替换 DIV 的内容仅在第一次工作
我使用以下 jQuery 来提取新数据并替换 DIV listdata 的内容
$(function(){
$('.refresh').click(function(event) {
event.preventDefault();
$.ajax({
url: "_js/data.php",
success: function(results){
$('#listdata').replaceWith(results);
}
});
});
});
该脚本由页面上的众多链接触发,例如:
<a href="" id="update1" class="refresh">Update 1</a>
<a href="" id="update2" class="refresh">Update 2</a>
由于某种原因,该脚本仅在第一次单击链接时起作用。后续单击不会刷新数据。
我见过各种修复方法,但没有任何效果。有什么建议吗?
I'm using the following jQuery to pull new data and replace the contents of the DIV listdata
$(function(){
$('.refresh').click(function(event) {
event.preventDefault();
$.ajax({
url: "_js/data.php",
success: function(results){
$('#listdata').replaceWith(results);
}
});
});
});
The script is triggered by numerous links on the page, such as:
<a href="" id="update1" class="refresh">Update 1</a>
<a href="" id="update2" class="refresh">Update 2</a>
For some reason the script only works on the first click of a link. Subsequent clicks do not refresh the data.
I've seen various fixes but nothing that I can get working. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我看来,您的问题在于使用
replaceWith
。您将在第一次调用
replaceWith
时删除与$('#listdata')
匹配的元素,因此后续刷新无法找到数据应该在的位置放置在文档中。你可以尝试类似的东西
或像这样链接
It looks to me like your problem is with using
replaceWith
.You're removing the element which matches
$('#listdata')
on the first call ofreplaceWith
, so subsequent refreshes can't find where the data is supposed to be placed in the document.You could try something like
or chained like this
如果您使用
replaceWith()
,您将完全用一个全新的元素替换#listdata
。如果
data
不是类似于的内容,则
#listdata
会在replaceWith()
。我想你应该使用html()
来代替。If you're using
replaceWith()
, you're replacing#listdata
with a brand new element altogether.If
data
isn't something like<div id="listdata"></div>
then#listdata
is disappearing after thereplaceWith()
. I'm thinking you should probably usehtml()
instead.您需要将链接上的 href 更改为 ...。这可以防止单击链接时浏览器刷新。
如果您这样做,您还需要在点击处理程序末尾添加“return false”以防止冒泡。
You'll need to change the href's on your links to <a href="#">...</a>. This prevents the browser from refreshing when you click the link.
If you're doing things this way, you'll also want to stick a "return false" at the end of the click handler to prevent bubbling.
尝试:
如果
.refresh
锚点位于#listdata
元素内,则委托是一个更优化的解决方案:Try:
If the
.refresh
anchors are inside the#listdata
element, then delegation is a more optimized solution: