我在一个页面上有很多元素,每个元素中都有一个带有数据标签的 div。每个元素都有一定的数据标记值,有些元素具有相同的值。
我试图在单击 div 时根据数据标记值对元素进行排序。出于某种原因,我无法找到最好的方法。这是我的代码:
$(document).ready(function ($) {
$(".tag-pill img").on('click', function() {
var tagClicked = $(this).attr("data-tag");
$('#page-card .col-lg-4').hide();
$('#page-card .col-lg-4').each(function() {
if ($(this + '[data-tag="' + tagClicked + '" ]').length > 0) {
$(this).show();
}
})
})
});
任何帮助将不胜感激!谢谢
最佳答案
这是一个工作片段:
const $set = $(".col-lg-4") // Cache for performance
$(".tag-pill img").click(e => {
let tagClicked = e.target.attributes["data-tag"].nodeValue
console.log(`tagClicked = ${tagClicked}`)
$set.show() // Show all
.find(`[data-tag='${tagClicked}']`) // Finds a subset
.hide() // Hide the subset
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tag-pill" data-tag="it works">
<img data-tag="It works!" src="http://via.placeholder.com/100x50" /> Click the image
</div>
<div class="col-lg-4">
<p data-tag="It works!">Should disappear</p>
<p data-tag="It works!">Should disappear</p>
<p>Should remain visible</p>
<p data-tag="It works!">Should disappear</p>
<p>Should remain visible</p>
<p data-tag="It works!">Should disappear</p>
</div>
您可以使用 e.target.attributes["data -tag"].nodeValue
关于javascript - 单击时仅显示与其具有相同数据属性的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48581262/