循环通过不工作的元素 [英] Looping through elements not working

查看:75
本文介绍了循环通过不工作的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查元素是否具有与所有其他元素匹配的数据属性值,但循环并不总是有效。

I want to check if this element has a matching data attribute value to all other elements, but the loop doesn't always work.

删除下面的代码。

HTML

<div class="list">
   <div class="target" data-post-id="1"></div>
   <div class="target" data-post-id="2"></div>
   <div class="target" data-post-id="1"></div>
   <div class="target" data-post-id="1"></div>
</div>

JS(事件与目标相关 class):

JS (event is tied to the target class):

if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
   // do stuff
}

显然,我不知道如何正确地循环它。解决方案是什么?

Clearly, I don't know how to loop through it properly. What's the solution?

推荐答案

您可以使用单行代码:

if ($(this).closest('.list').find('.target[data-post-id=' + $(this).data("post-id") + ']').not(this).length > 0) {
// there was at least one other element in the list with the same data-post-id as the clicked element
}

这篇关于循环通过不工作的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆