我有一个jquery移动列表视图,用户将单击其中一个li,这将激活我的删除代码。所有这些都起作用了。问题是,我需要将每删除的李数减少一个。
listview看起来如下(页面上有九个列表视图):
<div data-role="collapsible" data-collapsed="true" data-inset="true">
<h3>Robbery
<span id="rob_count" class="ui-li-count" style="float:right;">3</span></h3>
<ul id="robberyAlertList" data-role="listview">
<li id="1" class="robbery">Some text</li>
<li id="2" class="robbery">Some more text</li>
<li id="3" class="robbery">Still more text</li>
</ul>
</div> 单击li后,将调用我的delete函数,并在其内部(在删除提示符之后)执行以下操作:
var nCnt = $("#" +msg_id).closest( "span" ).text();
$("#" +msg_id).closest( "span" ).text(--nCnt);
$('#' +msg_id).remove();
$('#fetch-result').html("Alert was deleted!"); 我想要做的是在span (3)中获取文本,并将其缩小1。正在发生的是,li被删除,#fetch-结果被设置,但没有其他内容。我不认为我得到的跨度超过了李,我肯定没有得到3。
我的猜测是,我对.closest做得不对。
有什么建议吗?
发布于 2016-08-19 23:49:14
从元素本身开始,closest()逐父查找DOM树,因此它将找不到您要查找的span,因为它是父级兄弟(想想表亲)的子级。此外,与其尝试获取当前计数并减少其数量,我只需对其余的列表项进行计数,并将新的计数放在它的位置:
function removeMessage(msg_id) {
var $toRemove = $('#' + msg_id); // element to remove
var $list = $toRemove.parent('ul'); // element's parent
$toRemove.remove(); // remove it
var newCount = $list.find('li').length;
$list.closest('div').find('.ui-li-count').text(newCount); // get and show new count
}
removeMessage('1');<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-role="collapsible" data-collapsed="true" data-inset="true">
<h3>Robbery
<span id="rob_count" class="ui-li-count" style="float:right;">3</span></h3>
<ul id="robberyAlertList" data-role="listview">
<li id="1" class="robbery">Some text</li>
<li id="2" class="robbery">Some more text</li>
<li id="3" class="robbery">Still more text</li>
</ul>
</div>
https://stackoverflow.com/questions/39049049
复制相似问题