【发布时间】:2014-07-28 23:17:12
【问题描述】:
在我的应用程序中有一个包含国家数据的表格,它还使用分页。对于每一行,都有一个删除按钮,通过 ajax 触发一个函数,国家从数据库中删除,行向上滑动,表格根据我们所在的页面再次呈现。
这是我原来的功能:
$(document).on('click', '.glyphicon-remove', function(event) {
var thiz = $(this);
var id = thiz.next('input:hidden').val();
$.ajax({
url: '/country/' + id,
type: 'DELETE'
})
.done(function() {
thiz.parent().parent().parent()
.find('td')
.wrapInner('<div style="display: block;" />')
.parent()
.find('td > div')
.slideUp(200, function() {
thiz.parent().parent().remove();
if (curPage) {
if ($('.table > tbody > tr').length > 1) {
renderCountries(curPage);
} else {
var page = getURLParameter(curPage, 'page');
if (page !== '1') {
prevPage = previousPageURL(curPage, 'page');
renderCountries(prevPage);
curPage = prevPage;
} else {
renderCountries();
}
}
} else {
renderCountries();
}
});
});
});
然而,我发现slideUp()函数被执行了多次,搞砸了整个事情,我不知道原因,所以我改变了它,现在我使用delay():
$(document).on('click', '.glyphicon-remove', function(event) {
var thiz = $(this);
var id = thiz.next('input:hidden').val();
$.ajax({
url: '/country/' + id,
type: 'DELETE'
})
.done(function() {
thiz.parent().parent().parent()
.find('td')
.wrapInner('<div style="display: block;" />')
.parent()
.find('td > div')
.slideUp(200)
.delay(200, function() {
thiz.parent().parent().remove();
if (curPage) {
if ($('.table > tbody > tr').length > 1) {
renderCountries(curPage);
} else {
var page = getURLParameter(curPage, 'page');
if (page !== '1') {
prevPage = previousPageURL(curPage, 'page');
renderCountries(prevPage);
curPage = prevPage;
} else {
renderCountries();
}
}
} else {
renderCountries();
}
});
});
});
但是,现在在delay() 之后执行的函数被执行了两次。我不明白为什么会发生这一切,我想知道如何解决这个问题。
编辑:HTML
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Continent</th>
<th>Capital</th>
<th>Language</th>
<th>Population</th>
<th>Currency</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>asdfdsaf</td>
<td></td>
<td></td>
<td></td>
<td>0</td>
<td></td>
<td>
<form method="POST" action="http://localhost:8000/country/all" accept-charset="UTF-8" class="pull-right"><input name="_token" value="l2LCeqGRZARM6YUR6hqTgoKWNRRxAUcwspf4kf1v" type="hidden">
<span class="glyphicon glyphicon-remove btn btn-xs btn-danger"></span>
<input name="id" value="1" type="hidden">
</form>
</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
td 中有多少个 div?也许它只是为每个 div 执行?
-
嗯
div只是一个临时包装,所以 slideUp 工作。 -
你有小提琴之类的东西要测试一下吗?
-
curPage是什么?你永远不会在任何地方定义它。 (不要让你的函数依赖于隐藏的全局状态。)
标签: javascript jquery