类的目标特定实例

Target specific instance of class

本文关键字:实例 目标      更新时间:2023-09-26

我试图从用户单击的特定类的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");
});

考虑到您发布的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");
});

JS Fiddle demo.

为了确保被点击的元素是正确的类型(确保匿名函数在类名被删除后不会保持绑定,因为事件被绑定到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");
});

JS Fiddle demo.

引用:

  • on() .
  • removeClass() .