类的目标特定实例
Target specific instance of class
我试图从用户单击的特定类的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()
.
相关文章:
- ES6构造函数返回基类的实例
- KnockoutJS-组件-多个实例
- 为什么无法在TypeScript中导出类实例
- 如何在GoogleWeb工具包(GWT)中从JSNI调用接口(实例化)
- 为什么HTML5拖放的目标是孩子?(可排序列表)
- fluxxor向一个flux实例添加一组以上的操作
- 如何覆盖锚点元素's href目标,并在我点击转到目标javascript时删除其他错误
- 使用jQuery获取Dropzone实例/对象
- "实例范围”;TypeScript类的getter/setter
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- Href:当前DIV中的目标ID
- 如何在速度模板中获取LiferayPortlet实例id
- 同一项怎么可能在一个实例中未定义,却在另一个实例上定义
- 实例创建(JS)
- 显示模块模式在Knockout中设置模型的新实例
- 如何获取单选按钮的多个实例的选定单选按钮值
- 当使用extern和目标JavaScript时,我如何强制Haxe编译器使用require语句
- 多个语义 UI 弹出窗口,其中目标元素在每个实例的 atribute 中定义
- JqueryUI对话框打开处理onclick事件与旧的目标实例
- 类的目标特定实例