我有很多<li>
其中一些处于正常状态而一些部分处于突出显示状态的元素(具有“hasNews”类):
<ul class="companies">
@foreach (var item in Model)
{
<li id='company_@(item.Id)' data-id='@item.Id' @{if (item.hasNews) { <text>class="hasNews"</text>} } >
<a>@item.Name</a>
</li>
}
</ul>
当我点击任何<li>
时我想要,将其 Id 发送到 Controller ,将该公司设置为已读,如果回调为 true,则从该 <li>
中删除“hasNews”类。
我在 Controller 中有方法可以做到这一点。但我需要 jquery 的帮助来从单击的 <li>
中删除“hasNews”类如果回调为 true,则为 item。使用以下代码,我向 Controller 发送请求,执行操作并返回 false 或 true。但是那个<li>
项目仍然突出显示:
$('.companies li ').click(function (e) {
url = '@Url.Action("SetCompanyNewsAsRead", "Company")';
var data = { id: $(this).attr('data-id') };
$.post(url, data, function (result) {
if (result.success) {
$(this).removeClass('hasNews'); //this does not remove "hasNews" class.
}
});
});
如何解决这个问题?
编辑:
我想添加: <li>
之一项目是“当前”的。我是这样做的:
$('#company_' + currentItemId).addClass('current');
这项工作。这可以防止“hasNews”类删除吗?
最佳答案
问题是内部(回调)函数中的 this
与外部函数中的不同 - this
是根据函数的调用方式设置的,它绝对不是从包含函数继承的。将对其的引用保存在外部函数的变量中,内部函数可以访问它:
$('.companies li ').click(function (e) {
url = '@Url.Action("SetCompanyNewsAsRead", "Company")';
var theLI = this, // <--------- Save reference to this
data = { id: $(this).attr('data-id') };
$.post(url, data, function (result) {
if (result.success) {
$(theLI).removeClass('hasNews'); //this does not remove "hasNews" class.
}
});
});
有关 this
在 JavaScript 中如何工作的更完整说明,请查看 MDN .
编辑:要回答您的编辑,不,其他类的存在应该没有区别。
关于javascript - Jquery 删除突出显示的类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14890829/