我正在尝试从具有用户点击的特定类的div的特定实例中删除一个类。例如,我有一个类的三个实例,让我们说unread
,然后我想从这个div实例中删除一个类。它可能是一个非常简单的解决方案,但无法在任何地方找到答案。
我尝试使用$(this)
,但显然不起作用,它仍会从所有未读实例中删除该类。
用户基本上会点击div,它会将他们的消息标记为已读,从而添加一个新类,直观地向用户显示他们已阅读该消息。
HTML
<div class="sidebar bottom-sidebar mb15mob">
<h2 class="nmb">Debate Updates <span class="close-sidebar close-bottom-sidebar visible-xs visible-sm"><i class="fa fa-times"></i></span></h2>
<div class="mark-read">MARK ALL AS READ</div>
<ul class="step no-list-icon">
<li class="unread">
<h3>Obamacare</h3>
<p>I'm not entirely sure i agree with your sentiments there. I personally belie...</p>
</li>
<li class="unread">
<h3>Obamacare</h3>
<p>I'm not entirely sure i agree with your sentiments there. I personally belie...</p>
</li>
<li>
<h3>Zombie Invasion</h3>
<p>How can you be so sure that the government hasn't put aside money for the eventu...</p>
</li>
</ul>
</div>
的jQuery
下面的代码显然删除了所有未读的实例,但我只想删除该类的一个单击实例。希望这是有道理的。
$(".unread").click(function () {
$(".step.no-list-icon li").removeClass("unread-debate-message");
});
答案 0 :(得分:2)
鉴于您发布的jQuery,解决方案似乎很简单:
// selects all the elements of class "unread", and binds a click event-handler:
$(".unread").click(function () {
// this/$(this) will always be the item that was interacted with:
$(this).removeClass("unread");
});
为了确保点击的元素属于正确的类型(为了确保在删除类名后匿名函数不会保持绑定,因为事件绑定到DOM节点不到具有该类名的DOM节点),您可以改为使用委托事件处理,将点击检测/处理绑定到父元素并提供必须匹配的选择器:
// selecting the elements with the 'unread' class-name:
$(".unread")
// moving to their closest 'ul' ancestor element(s):
.closest('ul')
// using 'on()' to bind a click event-handler to that ancestor,
// the anonymous function will be triggered only if the clicked-element
// matches the selector (the second string):
.on('click', '.unread', function () {
// removing the 'unread' class from the clicked-element:
$(this).removeClass("unread");
});
参考文献: